javascript - 使setTimeout内的setTimeout停止

时间:2014-11-20 09:44:23

标签: javascript jquery

我有这段代码 -

function example() {

    var i = 0;

    function add() {
        i++;
    }

    setTimeout(function doSomething() {
        add();
        setTimeout(doSomething, 1000);
    }, 1000);
}

现在基本上我想通过按下按钮使“setTimeout”停止 - 任何想法我怎么可能这样做? 感谢任何帮助

3 个答案:

答案 0 :(得分:2)

您无需在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);
}

答案 1 :(得分:0)

您需要使用clearTimeout:

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

答案 2 :(得分:-1)

要清除“setTimeout”引起的延迟,请使用“clearTimeout”功能。 Check Here

相关问题