how to control for-loop exection in javascript [what should this javascript code do]

非 Y 不嫁゛ 提交于 2019-12-13 03:44:05

问题


can anyone please help me to figure out what this code javaScript code means

  (function(){
  for(var i=0;i<5;i++){
    setTimeout(console.log(i),1000);
  }
})();

回答1:


Your code basically calls a function which is gonna log

0

1

2

3

4

A single time, why ? Because setTimeout is actually running setTimeout(undefined, 1000) 5 times, according to the return value of console.log, it will not evaluate a function, so the instruction is just lost.

Though from what I understand of what the code tries to say, to make the code work well, you could delegate the iteration control to a self calling function delayed with setSimeout

(function self(times, delay) {
    self.config = self.config || {
        times: times,
        delay: delay,
        iteration: 0
    };

    ++self.config.iteration;

    if (self.config.iteration <= self.config.times) {
        console.log(self.config.iteration);
        setTimeout(self, self.config.delay);
    }
})(5, 1000);



回答2:


You have run into very common closure issue. To fix this you can have for example self invoked function. Also you should pass function handler to setTimeout instead of invoking console.log:

for(var i=0;i<5;i++){
    (function( i ) {
        setTimeout( function(  ) {
            console.log(i);
        },1000);
    })( i );
}

If you want to print to console numbers from 0 to 4 in 1000ms interval you should use setInterval function:

var intervalHandler = null
  , i = 0;
intervalHandler = setInterval( function() {
    console.log( i );
    if( i === 4 ) {
         clearInterval( intervalHandler );
         return;
    } 
    i++;
}, 1000 );



回答3:


for(var i=0;i<5;i++) //this code loop for five time before it break. i.e, it will execute this function for five time setTimeout(console.log(i),1000);. setTimeout() is a javascript function for delay and it going to delayed for 1s and it going to carry out action for console.log(i);.



来源:https://stackoverflow.com/questions/21465280/how-to-control-for-loop-exection-in-javascript-what-should-this-javascript-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!