// source:http://blog.abhiomkar.in/2010/07/03/javascript-code-challenge-by-dropbox-team/
// NOT correct
function countdown(num) {
for (var i = 0; i <= num; i += 1) {
setTimeout(function () {
document.writeln(num - i);
}, i * 1000);
}
}
countdown(5); // -1 -1 -1 -1 -1 -1
// Solutions to fix:
//1. use instance function insdie setTimeout()
function countdown1(num) {
for (var i = 0; i <= num; i += 1) {
setTimeout((function (m) {
document.writeln(num - m);
}(i)), i * 1000);
}
}
countdown1(5); // 5 4 3 2 1 0
//2. use bind() to bind the real-time 'num-i'
function countdown2(num) {
for (var i = 0; i <= num; i += 1) {
setTimeout(document.writeln.bind(document, num - i), i * 1000);
}
}
countdown2(5); // 5 4 3 2 1 0
//3. a solution to http://blog.abhiomkar.in/2010/07/03/javascript-code-challenge-by-dropbox-team/
var countdown3 = function (num) {
for (var i = 0; i <= num; i += 1) {
(function (i) {
setTimeout(function () {
document.writeln(num - i);
}, i * 1000);
})(i);
}
}
countdown3(5); // 5 4 3 2 1 0
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.