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
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).