我正在尝试通过单击按钮继续运行一个功能,然后使用另一个按钮暂停它的过程。我很确定它每隔3秒就会推动我的功能,但我该如何阻止呢?我很确定我使用的是clearInterval错误,而且我不确定我的“暂停”过程的思维过程是否就在这里....
我希望启动按钮继续将我的利润功能(返回一个数字)推送到我的列表数组。我想使用setInterval()来基本上防止自己崩溃,并让世界上的所有时间都按下暂停按钮。 以下是我遇到问题的代码:
var list = [];
var repeater;
$('#Start').click(function(){
if(userVal != 20) {
repeater = list.push(setInterval(function(){profits(userVal)},3000));
//setInterval(list.push(profits(userVal)), 3000);
}
});
$('#Pause').click(function(){
repeater = clearInterval(repeater);
return repeater;
});
答案 0 :(得分:0)
您提供给setInterval
的功能将每3000毫秒运行一次。然后,您可以使用setInterval
的返回值通过将其传递给clearInterval
来阻止其运行。
var repeater;
$('#Start').click(function(){
if(userVal != 20) {
repeater = setInterval(function(){
list.push(profits(userVal));
},3000);
}
});
$('#Pause').click(function(){
clearInterval(repeater);
});
答案 1 :(得分:0)
你应该这样做
var list = [];
var repeater;
$('#Start').click(function(){
if(userVal != 20) {
repeater = setInterval(function(){
var temp = profits(userVal);
list.push(temp);
},3000);
}
});
暂停使用clearInterval()
$('#Pause').click(function(){
clearInterval(repeater);
});
答案 2 :(得分:0)
setInterval
会返回一个数字参考,用于清除时间间隔,而不是您希望返回的值。请改用:
var list = [];
var repeater;
$('#Start').click(function(){
if(userVal != 20)
repeater = setInterval(function(){
list.push(profits(userVal));
},3000));
});
$('#Pause').click(function(){
clearInterval(repeater);
// It's a good idea to set the interval to a false-y value so it can be used to detect if the interval is still active. void 0 just returns undefined
repeater = void 0;
});
答案 3 :(得分:0)
alert()
会暂停您的JavaScript,直到您按"OK"