SetInterval重新运行函数

SetInterval rerun function

本文关键字:函数 重新运行 SetInterval      更新时间:2023-09-26

我有以下javascript函数:

function One(){
    setInterval(function(){ //piece of code },3000);
    setInterval(function(){ //piece of code },3000);
    setInterval(function(){ One(); },3000);
}

正如你所看到的,我希望第一段代码在3秒后执行,然后它跳到第二个setInterval并在3秒后运行代码,然后它跳到第三个setInterval,重新运行整个函数,但它不起作用…它运行第一段代码,第二段代码,在第三段,它不再重新运行函数,而是继续执行第二段代码。

我想你要setTimeout代替。setInterval()会一次又一次地调用它,你只希望每次调用One()时它调用一次。然后你可以把它们链接在一起,像这样:

function One(){
    setTimeout(function(){ 
        //piece of code A
        setTimeout(function(){ 
            //piece of code B
            setTimeout(function(){ 
                One(); //restart
            },3000);
        },3000);
    },3000);
}