setTimeout

    xiaoxiao2022-06-22  16

    Use:Call functions in specific time.

    Grammar:setTimeout(code,millisec) <script> setTimeout("console.log('one second')",1000);//one second </script>

    This function will run only once!

    Attention: You will be confused to see the following codes:

    <script> for(var i=0;i<5;i++){ console.log(i); setTimeout(function(){ console.log(i); },5000); } </script>

    Results will be like this: 0,1,2,3,4,5,5,5,5,5,5(5 will appear five times in five seconds after 4 appeared). Because function in setTimeout does not run immediately.It will delay and then the variable i is already 5. If you want to solve this problem,use codes like this: (1):

    <script> for(var i=0;i<5;i++){ (function(j){ setTimeout(function(){ console.log(j); },5000); })(i); } </script>

    (2)

    <script> for(let i=0;i<5;i++){ setTimeout(function(){ console.log(j); },5000); } </script>

    Results will be like this: 0,1,2,3,4.(The sequence may not be in order).

    转载请注明原文地址: https://ju.6miu.com/read-1122894.html

    最新回复(0)