setTimeout with Loop in JavaScript

后端 未结 9 1582
挽巷
挽巷 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:15

    Easy fix here is to utilize es6 let local variable. Your code will look almost the same except it will do what you expect :)

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

    Or you could create a recursive function to get that job done, as following:

    function timedAlert(n) {
      if (n < 3) {
        setTimeout(function() {
            alert("Count = " + n);
            timedAlert(++n);
        }, 1000);
      }
    }
    
    timedAlert(0);
    

提交回复
热议问题