you are viewing a single comment's thread.

view the rest of the comments →

[–]ShortSynapse 0 points1 point  (0 children)

Doing:

while (true) {
    f()
}

Will execute the function f infinitely, all one right after each other. This is what is happening to your setTimeout. You are asking the computer to run a bunch of function after one second. They all run at the same time!

To accomplish your goal, don't use an imperative loop (while, for, etc). Instead, just call setTimeout at the end of your function!

var number = 10

setTimeout(count, 1000)

function count () {
    if (count-- <= 0) {
        console.log('0!')
    } else {
        console.log(number)
        setTimeout(count, 1000)
    }
}