如何在JavaScript中暂停连续运行的函数?

如何在JavaScript中暂停连续运行的函数?,javascript,jquery,Javascript,Jquery,我试图让一个函数连续运行,只需单击一个按钮,然后再单击另一个按钮来暂停它。我很确定它每3秒钟就推一次我的功能,但我该如何阻止它呢?我很确定我使用clearInterval是错误的,我也不确定我“暂停”这个过程的思维过程是否就在这里 我希望“开始”按钮继续将我的利润函数(返回一个数字)按到我的列表数组中。我想到了使用setInterval()从根本上防止自己崩溃,并让自己在世界上所有的时间按下暂停按钮。 以下是我遇到问题的代码: var list = []; var repeater; $('#S

我试图让一个函数连续运行,只需单击一个按钮,然后再单击另一个按钮来暂停它。我很确定它每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;
});

您提供给
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);
});
你应该做什么

var list = [];
var repeater;
$('#Start').click(function(){   
if(userVal != 20) {
    repeater = setInterval(function(){
                          var temp = profits(userVal);
                          list.push(temp);
               },3000);
}
});
要暂停,请使用
clearInterval()


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;
});

alert()
将暂停您的javascript,直到您按
“确定”

list.push在做什么?对不起,我刚刚为我的问题添加了更多细节。list.push基本上是将“我的利润”函数生成的数字添加到我的列表数组中。请检查下面的代码。对不起,为我的问题添加了更详细的内容。@Falconeyi这是您的意图吗?
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;
});