Javascript setTimeout function starts executing too many times - Stack Overflow

I created a loop with setTimeout function and it es to a problem after 2nd or 3rd step it call's i

I created a loop with setTimeout function and it es to a problem after 2nd or 3rd step it call's itself because it starts excecuting twice at the time. This is what my function looks like:

var value = 70, 
    intervalID = null;

function interval() {
  intervalID = setTimeout(countDown, 1000);
}

function countDown() {
  value--;
  if(value > 0) {
    clearTimeout(intervalID);
    interval();
  } else {
    endInterval();
  }
}

function endInterval() {
  // do something
}

If I console the variable value its 69, 68 and after that it starts decreasing variable value twice in one function call. I'm not calling function countDown() anywhere but from one place.

What could be the problem?

Edit: this code works now.

I created a loop with setTimeout function and it es to a problem after 2nd or 3rd step it call's itself because it starts excecuting twice at the time. This is what my function looks like:

var value = 70, 
    intervalID = null;

function interval() {
  intervalID = setTimeout(countDown, 1000);
}

function countDown() {
  value--;
  if(value > 0) {
    clearTimeout(intervalID);
    interval();
  } else {
    endInterval();
  }
}

function endInterval() {
  // do something
}

If I console the variable value its 69, 68 and after that it starts decreasing variable value twice in one function call. I'm not calling function countDown() anywhere but from one place.

What could be the problem?

Edit: this code works now.

Share Improve this question edited Aug 29, 2012 at 10:59 JanHocevar asked Aug 29, 2012 at 10:39 JanHocevarJanHocevar 1992 silver badges9 bronze badges 3
  • 3 Works fine for me - jsfiddle/wZ3GM You sure you aren't calling the initial function twice? – Richard Dalton Commented Aug 29, 2012 at 10:42
  • Actually a loop you didn't wrote in you code or the "timeout loop" created? – Prusse Commented Aug 29, 2012 at 10:45
  • I had to clear timeout every time I called it again and it started working. Thanks for the tips – JanHocevar Commented Aug 29, 2012 at 10:56
Add a ment  | 

1 Answer 1

Reset to default 5

I'd remend you to "sanitize" the timeouts by stopping previous one.

function interval() {
  clearTimeout(intervalID);
  intervalID = setTimeout(countDown, 1000);
}

However it looks like control of symptoms instead of sickness' cause. So it would be better to detect the cause of the issue.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744909937a4600484.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信