Using setTimeout and an integer in a for loop

前端 未结 1 1678
失恋的感觉
失恋的感觉 2020-12-12 02:08

I have a button with id play.

I want a countdown on that button with this code. But for some reason I can\'t get this to work.

var time         


        
1条回答
  •  有刺的猬
    2020-12-12 02:50

    Use this :

    for(var i = seconds; i>0; i--) {
        (function(i){
          setTimeout(function() {
              countdown.text("" + i); }, timeoutTime);
        })(i);
        timeoutTime += 1000;
    }
    

    Your problem was that i changes and you were always calling with the last value of i, because the callback you pass to setTimeout is called after the loop finishes.

    The classic solution is to use a closure to keep another variable (here with the same name i) having the desired value. It works because this is a different function for each iteration (the scope of a variable is either the global scope or the function where it is declared).

    0 讨论(0)
提交回复
热议问题