清除全局函数内函数的超时

时间:2017-10-31 18:34:04

标签: javascript jquery function cleartimeout

我已经设置了一个函数,该函数使用名称myFunction加载文档。其中有5个功能,具有不同的超时。我想点击我的html代码中id为#btn的按钮,清除第3和第4个函数的时间。这是我的代码

<doctype! HTML>
<html>
<head>
<title>
My Page
</title>
<script src="jquery-3.2.1.js">
<script src="myScript.js">
<script type="text/javascript">
$(document).ready(myFunction);
</script>
</head>
<body>
<button id="btn">
</body>
</html>

myScript.js位于

之下
function myFunction(){
setTimeout(function function1(){
 // do stuffs
}, 5000);
setTimeout(function function2(){
 // do stuffs
}, 10000);
setTimeout(function function3(){
 // do stuffs
}, 15000);
setTimeout(function function4(){
 // do stuffs
}, 20000);
setTimeout(function function5(){
 // do stuffs
}, 25000);
}

3 个答案:

答案 0 :(得分:2)

要清除超时,必须将其分配给保存引用的变量。这是一个例子:

var t1,t2,t3,t4,t5;

function myFunction(){
    t1 = setTimeout(function function1(){
     // do stuffs
    }, 5000);
    t2 = setTimeout(function function2(){
     // do stuffs
    }, 10000);
    t3 = setTimeout(function function3(){
     // do stuffs
    }, 15000);
    t4 = setTimeout(function function4(){
     // do stuffs
    }, 20000);
    t5 = setTimeout(function function5(){
     // do stuffs
    }, 25000);
}

function myClearFunction(){
    clearTimeout(t3);
    clearTimeout(t4);
}

从按钮调用myClearFunction()以清除第三个和第四个计时器。

答案 1 :(得分:2)

您可以使用clearTimeout。这是一个功能演示:

&#13;
&#13;
var timer1 = setTimeout(function() {
  console.log('timer1');
}, 5000);
var timer2 = setTimeout(function() {
  console.log('timer2');
}, 10000);
var timer3 = setTimeout(function() {
  console.log('timer3');
}, 15000);
var timer4 = setTimeout(function() {
  console.log('timer4');
}, 20000);
var timer5 = setTimeout(function() {
  console.log('timer5');
}, 25000);

document.getElementById('x').addEventListener('click', function() {
  clearTimeout(timer3);
  clearTimeout(timer4);
});
&#13;
<button id="x">Stop Timer 3 and 4</button>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

SetTimeout返回一个值,保存为计时器3和4,然后点击按钮点击取消那些。确保在调用clear之前检查3-4的值是否已定义。

Return Value:   A Number, representing the ID value of the timer that is set. Use this value with the clearTimeout() method to cancel the timer

来自https://www.w3schools.com/jsref/met_win_settimeout.asp