function countdown (num) {
for (var i = 0; i <= num; i += 1) {
var make_cb = function (n) {
return function () {alert(num - n)};
}
setTimeout(make_cb(i), i * 1000);
}
} function countdown (num) {
for (var i = 0; i <= num; i += 1) {
var make_cb = function (n) {
return function () {alert(num - n)};
}
setTimeout(make_cb(i), i * 1000);
}
} function countdown(num) {
if(num < 0) {
return;
}
setTimeout(function() {
alert(num);
countdown(num - 1);
}, 1000);
}
Note: I'm aware that the dropbox version shows the first alert without any delay, whereas this waits a second before showing anything. This is slightly different behavior, but arguably acceptable. function countdown(n) {
if(n >= 0) {
alert(n);
setTimeout(function() {countdown(n-1);}, 1000);
}
} function countdown (num) {
for (var i = 0; i <= num; i += 1) {
setTimeout(function (i) {
return function(){ alert(num - i); }
}(i), i * 1000);
}
}
countdown(5);alert(num--);
LoL.
EDIT: On second thought, does anyone even know if the scenario I mentioned above is plausible? I changed the alerts to console.logs and I'm finding it pretty damn impossible to not get the expected results using the "cheater way" even for large values of num.
And no, I don't think the potential problem you see is much of a problem at all. The function will keep executing even if the timers fire. As long as the timeouts execute in order and the countdown function is able to queue them in less time than they take to execute, it will work.
function countdown (num) {
for (var i = 0; i <= num; i += 1) {
let (j = num - i){
setTimeout(function () {
alert(j);
}, i * 1000);
}
}
}