是否从超时内开始间隔是一个问题

Is starting an interval from within a timeout an issue

本文关键字:问题 一个 超时 开始 是否      更新时间:2023-09-26

在我网站上的iframe中,我想运行一个轮询函数。我希望它在页面加载后运行 800 毫秒,然后每 100 毫秒运行一次。

我目前正在这样做,但想知道它是否会导致任何问题:

 window.setTimeout(function(){
            foo();
            window.setInterval(function(){
                foo();
            }, 100)
        }, 800);

setTimeout所做的只是在指定的延迟后执行其中包含的函数。它不会对您的setInterval通话产生任何影响。将setInterval放在setTimeout内的唯一区别是,它只会在 800 毫秒延迟过后触发。

如果您的foo函数设计为始终重复自身,则可以改为在该函数中放置第二个setTimeout

function foo() {
    window.setTimeout(foo, 100);
}

现在您需要做的就是在setTimeout中调用foo()一次:

window.setTimeout(foo, 800);

不过,这几乎完全取决于个人喜好。显然,如果您的foo函数也被设计为在其他地方调用,则此方法并不理想。


演示

var count = 0,
    elem = document.querySelector('p');
function foo() {
  elem.innerHTML = ++count;
  window.setTimeout(foo, 100);
}
window.setTimeout(foo, 800);
<p>Count will be displayed here after the 800ms timeout finishes...</p>