简体   繁体   中英

setTimeout Node v0.12 fires immediately in for loop?

Out of all the questions I have seen on this site about setTimeout the majority of them people are executing the method in a setTimeout declaration. I am not doing this.

Code:

var nums = [1,2,3,4,5,6,7,8,9];

for(var i=0; i < nums.length; i++){
  setTimeout(function(num){
    var url = getUrl(num);
    //query(url); // prints out query operation and data return
    console.log(num);
  }, 1000, nums[i]);
}

When running the command to start the app, query will execute all items in the array no matter how large I set the millisecond delay. When running this code with printing out to console I get the same effect. Am I doing this wrong? Can anyone else duplicate this?

I created an app that would run setInterval to test api throttling, and it works as expected. I am thinking I may be missing some kind of backend knowledge about node with setTimeout and loops? setTimeout Docs

The docs do say that it won't guarantee the time that it will execute the callback, but I have 120 items that it is going to fire logging on and it fires them all at once.

since those function setTimeout or setInterval works asynchronously, You have to call the next loop in the setTimeout/setInterval callback function.

var _i = 0
var doQuery = setInterval(function(){
  if(_i == nums.length) clearInterval(doQuery);
  var url = getUrl(nums[_i]);
  query(url);
  _i++;
},1000);

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