简体   繁体   中英

Unexpected behavior in setTimeOut in for loop

I'm trying to log numbers to the console on specific intervals. However, what occurs instead is that it waits the set interval, then logs everything out as normal.

I've tried two different ways to create a closure both work. But do nothing in regards to the delayed console.log.

 function timeOutLoop(x){ for(var i = 0; i<=x; i++){ (function(n){ setTimeout(function(){console.log(n)},5000) })(i) setTimeout(function(num){ return function(){ console.log(num) } }(i),1000) } } timeOutLoop(33) 

I was under the impression that each setTimeout will go on the event queue with the context provided by the closure. What gives?

Since the loop basically executed instantly, with the first one there will not be much of a difference since the time is in milliseconds and as for the second one, they will all execute after 1 second.

Using a combination of the two methods, you can achieve it:

  function timeOutLoop(x) { for(var i = 0; i <= x; i++) { setTimeout(function(num) { return function(){ console.log(num); } }(i), i * 1000); } } timeOutLoop(33) 

setTimeouts start at the same time so if you want to start a timeout after another you can create a recursive function :

function timeOutLoop(x, i=0){
   if(i<=x){
      console.log(i);
      i++;
      setTimeout(function(){timeOutLoop(x, i)},1000);
   }
}
timeOutLoop(33)

You can set timeout value to whatever you like.

 function timeOutLoop(x){ for(let i = 0; i<=x; i++){ setTimeout(function(){console.log(i)},i * 1000); } } timeOutLoop(33); 

Is this what you are looking for? Change from var to let in order to keep the variable i intact inside the loop scope. More here about let vs var .

Also multiply i by 1000 to print every second until reaching 33.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM