我使用setInterval每隔几秒钟运行一个函数(做一些AJAX的事情)。然而,我还有另一个函数也在调用它。
setInterval(myFunc(), 5000);
function buttonClick() {
// do some stuff
myFunc();
}大多数情况下它是有效的,但是有时这个函数会同时被调用两次,导致两次得到完全相同的结果,这是我不想要的。
我想我必须使用clearTimeout:
var interval = setInterval(myFunc(), 5000);
function buttonClick() {
clearTImeout(interval);
// do some stuff
myFunc();
interval = setInterval(myFunc(), 5000);
}但是,这会导致函数暂停。因为它是从另一个函数调用的,所以一些代码永远不会执行。我如何防止这种情况发生?
发布于 2011-03-29 03:32:11
然而,有时这个函数会被同时调用两次,导致两次得到完全相同的结果,这是我不想要的。
浏览器上的JavaScript是单线程的(禁止使用新的web workers内容,但这在这里无论如何都不适用)。你的函数在运行时永远不会被调用。(更多信息见下文。)
在您的各种代码引号中,您正在调用myFunc,而您只是想引用它。例如:
var interval = setInterval(myFunc(), 5000);应该是
var interval = setInterval(myFunc, 5000);
// ^--- No parentheses如果你纠正了这一点,你取消超时的代码将会工作:
var interval = setInterval(myFunc, 5000);
function buttonClick() {
clearTImeout(interval);
// do some stuff
myFunc();
interval = setInterval(myFunc, 5000);
}但是没有理由这样做,myFunc在运行时无论如何都不能被调用。
如果myFunc触发了一些将异步完成的操作(例如,一个ajax调用),则上面的将不会帮助(原因很简单,myFunc将启动该进程,然后返回;该进程将单独完成)。在这种情况下,最好的办法是让myFunc自己安排它的下一次调用:
function myFunc() {
// Do my work...
// Schedule my next run
setTimeout(myFunc, 5000);
}...and根本不使用setInterval。
发布于 2011-03-29 03:31:14
除非myFunc返回一个函数,否则我会这样做(也可以使用clearInterval代替clearTimeout):
var interval = setInterval(myFunc, 5000);
function buttonClick() {
clearInterval(interval);
// do some stuff
myFunc();
interval = setInterval(myFunc, 5000);
}setInterval在其参数中需要一个函数。您可以使用myFunc()调用函数。因此,无论myFunc返回什么,都会传递给setInterval,这可能不是您想要的结果。
发布于 2011-03-29 03:38:43
我意识到已经有几个解决方案,但我想展示一个比“这么做”稍微多一点的解决方案。我倾向于通过例子来学习,并认为我会推广同样的做法。这就是说,demo is here,但我也会试着解释。
// Here we assign the function to a variable that we can use as an argument to the
// setInterval method.
var work = function(){
// performing a very simple action for the sake of demo
$('#log').append('Executed.<br />');
};
// this is a variable that is essentially used to track if the interval is or is
// not already running. Before we start it, we check it. Before we end it, we also
// check it. Let's start off with it started though
var worker = setInterval(work, 5000);
// bind to the start button
$('#start').click(function(){
// Test: is the worker already running?
if (worker)
// Yes it is, don't try to call it again
$('#warn').text('Timer already running!');
else{
// no it's not, let's start it up using that function variable we declared
// earlier
worker = setInterval(work,3000);
$('#warn').text('Started!');
}
});
// bind to the stop button
$('#stop').click(function(){
// test: is the worker running?
if (!worker)
// no, so we can't stop it
$('#warn').text('Timer not running!');
else{
// yes it's working. Let's stop it and clear the variable.
clearInterval(worker);
worker = null;
$('#warn').text('Stopped.');
}
});https://stackoverflow.com/questions/5463986
复制相似问题