最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - setTimeout() inside setInterval() sequence fires off only once - Stack Overflow

programmeradmin1浏览0评论

Granted the following piece of code:

function updateOdometers(odometers) {
    setTimeout(function(){
        odometers[1].update(odometers[1].value + 10);
    }, 500);

}

setInterval(updateOdometers(odometers), 2000);

For whatever reason, this code updates the value of odometer only once, rather than every 2000ms with a delay inside. Googling/SO-ing around didn't get me much of a result. Any ideas?

Granted the following piece of code:

function updateOdometers(odometers) {
    setTimeout(function(){
        odometers[1].update(odometers[1].value + 10);
    }, 500);

}

setInterval(updateOdometers(odometers), 2000);

For whatever reason, this code updates the value of odometer only once, rather than every 2000ms with a delay inside. Googling/SO-ing around didn't get me much of a result. Any ideas?

Share Improve this question asked Mar 3, 2015 at 20:36 favorettifavoretti 30.2k4 gold badges51 silver badges62 bronze badges 4
  • Why are you trying to do this? – Bergi Commented Mar 3, 2015 at 20:39
  • 2 Duplicate of stackoverflow./questions/28837247/… – Telokis Commented Mar 3, 2015 at 20:40
  • Blah, didn't find the original question you're referring to. – favoretti Commented Mar 3, 2015 at 20:55
  • @Bergi: this is a not very sane sanitized piece of code. I have a number of odometers I need to update. The update has to happen every 6 seconds and inner odometers need to update one by one. Makes sense? – favoretti Commented Mar 3, 2015 at 21:03
Add a ment  | 

1 Answer 1

Reset to default 7

This line :

setInterval(updateOdometers(odometers), 2000);

should be

setInterval(function () {updateOdometers(odometers);}, 2000);

Otherwise you will be calling updateOdometers(odometers) and passing its result to setInterval.

发布评论

评论列表(0)

  1. 暂无评论