Given the following javascript code:
function countdown (num) {
for (var i = 0; i <= num; i += 1) {
setTimeout(function () {
alert(num - i);
}, i * 1000);
}
}
countdown(5);
The desired result is a countdown from 5 to 0 using alert messages. Explain why the code only alerts -1, then fix the code so it works as expected.
I found the above javascript quiz and i really don't know how to solve it. I know it's anonymous functions and it has something to do with the variables scope but i consider it a great opportunity to learn if someone could explain me why it's not working and what needs to be done in order to work. I seek the theory behind the problem and the solution.
I know i can just read about Anonymous functions but an explanation using a "real problem" will help me visualize the problem and understand it better.