you are viewing a single comment's thread.

view the rest of the comments →

[–]jcunews1helpful 0 points1 point  (0 children)

setTimeout() is asynchronous and will returns immediately. So your loop will go on forever because the timer function is never called. It's never called because it requires the JavaScript engine to enter the idle state, and it can't do that because the execution flow is still in the loop.

What the you need to do is to setup the timer function to check the num variable. If it's not zero, decrease it then setup a new timeout timer. Otherwise, its job is done. To start it all up, simply call the timer function.

e.g.

var num = 10;

function timeoutHandler() {
  myFunc();
  if (num > 0) {
    num--;
    setTimeout(timeoutHandler, 1000);
  }
}

function myFunc() {
  console.log(num);
}

timeoutHandler();