setTimeout with Loop in JavaScript

后端 未结 9 1688
挽巷
挽巷 2021-01-05 16:08

I have a very trivial question. For a simple loop with setTimeout, like this:

for (var count = 0; count < 3; count++) {
    setTimeout(function() {
               


        
9条回答
  •  青春惊慌失措
    2021-01-05 16:08

    think about it like that:

    AFTER the 1000*n miliseconds are over, what will be the value of count?

    of course it will be 3, because the foor loop ended way earlier than the timeout of 1000*n ms.

    in order to print 1,2,3 you'll need the following:

    for (var count = 0; count < 3; count++) {
        do_alert(num);
    }
    
    function do_alert(num) {
        setTimeout(function() {
            alert("Count = " + num);
        }, 1000 * num);
    }
    

    a different approach is to make it a closure function (explained well in JavaScript closures vs. anonymous functions)

    for (var count = 0; count < 3; count++) {
        (function(num){setTimeout(function() {
            alert("Count = " + num);
        }, 1000 * num)})(count);
    }
    

    these two code samples will actually work similarly.

    the first sample calls a named function (do_alert) each iteration.

    the second sample calls a CLOSURE anonymous function (which is just like do_alert) each iteration.

    it's all a matter of SCOPE.

    hope that helps.

提交回复
热议问题