Answer the question
In order to leave comments, you need to log in
What to do to make it work?
I'm just learning js and have been struggling with it for an hour now. It is necessary that there be a countdown of 4 ... 3 ... 2 .. 1 .. but instead, when the button is pressed, the number 1 immediately flashes. What is the problem.
function kakafka() {
var a = document.getElementById("out");
setTimeout(function() { a.innerHTML = "4" }, 2000);
setTimeout(function() { a.innerHTML = "3" }, 2000);
setTimeout(function() { a.innerHTML = "2" }, 2000);
setTimeout(function() { a.innerHTML = "1" }, 2000);
}
Answer the question
In order to leave comments, you need to log in
Everything is simple. You can get confused with timeouts and recursions as in the examples above. And you can do it logically correctly - with an interval, as in this example:
var counter = 4;
var inter = setInterval(function() {
a.innerHTML = counter--;
if (!counter) clearInterval(inter);
}, 2000);
See, JS is asynchronous. This means all functions that have "idle time" run at the same time (in your case it's setTimeout. It's an asynchronous function).
In your code, all setTimeouts are initialized and run. And after that, everything is executed after an equal period of time (2 s).
If you come from python or PHP (or other language without Event Loop). Then there all the functions (pause, sleep, etc.) stop the execution of the code. In JS, they just run and continue execution.
Perhaps it will be useful:
javascript.ru/unsorted/async
https://www.google.ru/webhp?sourceid=chrome-instan...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question