N
N
Nicholas Komarov2015-10-10 02:57:41
JavaScript
Nicholas Komarov, 2015-10-10 02:57:41

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

2 answer(s)
P
profesor08, 2015-10-10
@GloomySpodgeBob

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

H
HoHsi, 2015-10-10
@HoHsi

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 question

Ask a Question

731 491 924 answers to any question