有没有办法让setInterval在经过一定时间后才开火?

时间:2017-09-02 02:07:59

标签: javascript

我有

var slideIn1 = setInterval(slideBarIn1, 1)

我也有

var slideIn2 = setInterval(slideBarIn2, 1)

我希望第二个setInterval在slideIn1上使用clearInterval后几秒钟生效。
我尝试使用setTimeout在几秒钟后调用第二个setInterval,但是在页面加载时会触发setInterval ...有什么建议吗?

function slideBarIn1(){
    barPosition1 = barPosition1 - 0.7;
    verticalBar.style.left = barPosition1+"px";

    if (barPosition1 < (-320)) {
        clearInterval(slideIn1);
    }   
}

function slideBarIn2(){
    barPosition2 = barPosition2 - 0.7;
    horizontalBar.style.top = barPosition2+"px";

    if (barPosition2 < (-320)) {
        clearInterval(slideIn2);
    }   
}

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你想: 1)等待页面加载。 2)等待1秒钟。 3)执行slideBarIn1。 4)等待1秒钟。 5)执行slideBarIn2。 6)等待(未指定)秒。 7)返回步骤3 - 执行slideBarIn1。

我建议使用setInterval或setInterval和setTimeout的组合进行切换,并将其替换为策略性地放置的&#39; setTimeout&#39。

下面是一个应该在slideBarIn1和slideBarIn2之间交替的示例,其间有1秒的延迟。

&#13;
&#13;
/* Wait until page loaded and then start the first sequence */
window.onload = function() {
// Execute slideBarIn1 in 1 second (1000 milliseconds)
    setTimeout(slideBarIn1, 1000); 
};
function slideBarIn1() {
    //Do whatever slideBarIn1 needs to do
    //And then, before leaving this function
    // start a timer for slideBarIn2
    setTimeout(slideBarIn2, 1000);
}
const delayBetweenTwoAndOne = 1000; // set to zero for no delay
function slideBarIn2() {
    // Do whatever slideBarIn2 needs to do
    // If you wish to keep the loop going, 
    // you can now set another timer for slideBarIn1
    setTimeout(slideBarIn1, delayBetweenTwoAndOne); 
}
&#13;
&#13;
&#13;