在设置超时中设置超时以停止



我有这个代码 -

function example() {
    var i = 0;
    function add() {
        i++;
    }
    setTimeout(function doSomething() {
        add();
        setTimeout(doSomething, 1000);
    }, 1000);
}

现在基本上我想通过按下按钮使"setTimeout"停止 - 任何想法我该怎么做?感谢您的任何帮助

你不需要在setTimeout里面调用setTimeout。您可以使用setInterval,它将每秒调用。请参阅下面的代码以使用clearInterval()停止间隔

var timeInterval = '';
function example() {
    var i = 0;
    function add() {
        i++;
    }
    //store time Interval  using variable
    timeInterval = setInterval(function() {
        add();
        //setTimeout(doSomething, 1000);-- remove this
    }, 1000);
}
function buttonClick()
{
  //clear time out
  window.clearInterval(timeInterval);
}

你需要使用 clearTimeout:

var timer = setTimeout(doSomething, 1000); //store setTimeout in a variable
//now when you need clear it:
clearTimeout(timer)

要清除由"setTimeout"引起的延迟,请使用"clearTimeout"函数。在这里查看

最新更新