Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript-在setTimeout中设置setTimeout以停止_Javascript_Jquery - Fatal编程技术网

javascript-在setTimeout中设置setTimeout以停止

javascript-在setTimeout中设置setTimeout以停止,javascript,jquery,Javascript,Jquery,我有这个密码- function example() { var i = 0; function add() { i++; } setTimeout(function doSomething() { add(); setTimeout(doSomething, 1000); }, 1000); } 现在基本上我想通过按下一个按钮使“设置超时”停止-有什么想法我可以怎么做? 感谢您提供的任何帮助您需要使

我有这个密码-

function example() {

    var i = 0;

    function add() {
        i++;
    }

    setTimeout(function doSomething() {
        add();
        setTimeout(doSomething, 1000);
    }, 1000);
}
现在基本上我想通过按下一个按钮使“设置超时”停止-有什么想法我可以怎么做?
感谢您提供的任何帮助

您需要使用clearTimeout:

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

您不需要在
setTimeout
内部调用
setTimeout
。您可以使用
setInterval
,它将每秒调用一次。请参阅下面的代码,使用
clearInterval()


要清除“设置超时”引起的延迟,请使用“clearTimeout”功能。

如果重复执行相同的操作,请使用
setInterval
。↑↑↑ <代码>var间隔=设置间隔(添加,1000)和调用
清除间隔(interval)单击按钮但注意上下文,您可能希望删除示例函数上下文或在全局上下文中设置
间隔
(例如,在声明中删除
var
)否,
setTimout
执行一次。你是想把它改成一个
setInterval
?@Jamiec,是的,你是对的。我已经更新了我的答案。。。谢谢:)那么在这个例子中,命名函数
doSomething
(是否有?)就没有意义了,反正+1
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);
}