2012-01-14 27 views
4

有没有办法检查clearTimeout是否成功。明确超时成功?

我有一个JavaScript函数,它以30秒的间隔异步运行。它是一个自我调用函数,它使用setTimeout()在循环中重复它自己。在特定情况下,我需要在发生某些事件后调用此函数。因此,我首先clearTimeout并再次调用该函数。但是我不知道我是否能够成功地清除之前的循环,或者现在是否已经开始了两个独立的循环。我可以做这样的事吗? :

if(clearTimeout(timer)) 
alert("cleared"); 
+1

如果您传递了正确的参数,则清除了循环。但是如果你想感到更安全,考虑将另一个参数传递给“true”或“false”的函数。如果“false”,该函数不应该设置循环。 – Jon 2012-01-14 04:10:49

+0

我觉得好像应该有一个很好的方式来跟踪你的计时器的状态,并始终确信你的clearTimeout是成功的。这是一个简单的小提琴让人们开始。 http://jsfiddle.net/ASYgU/ – mrtsherman 2012-01-14 04:37:31

+0

@mrtsherman嗯,我试着弄了一下代码;输出可变定时器的值。原来,这是一些增加的数字。有一点是肯定的:'if(timer)'语句总是返回true,不能用来检查定时器是否在运行。但它可以用来追踪循环运行的次数。 [更新的小提琴](http://jsfiddle.net/roopunk/ASYgU/4/) – roopunk 2012-01-15 10:36:36

回答

4

“有没有一种方法来检查clearTimeout的成功。”

没有,有没有保持状态,您可以查看,但如果你正确地管理你的计时器,它不应该是一个问题。


你可以创建自己的状态计时器对象,我想......

var _slice = Array.prototype.slice; 

    // substitute for setTimeout 
function myTimer(fn,ms) { 
    var args = _slice.call(arguments,2), 
     timer_state = { 
      complete: false, 
      timer: setTimeout(function() { 
       timer_state.complete = true; 
       fn.apply(this, args); 
      }, ms) 
     }; 
    return timer_state; 
}; 

    // substitute for clearTimeout 
function clearMyTimer(timer_obj) { 
    timer_obj.complete = true; 
    clearTimeout(timer_obj.timer); 
}; 

清除定时器的例子......让它运行的

// create a timer 
var timer = myTimer(function() { 
    console.log('timer is done'); 
}, 1000); 

console.log(timer.complete); // complete? false 

clearMyTimer(timer); // clear it 

console.log(timer.complete); // complete? true 

例...

// create a timer 
var timer = myTimer(function() { 
    console.log('timer is done'); 
}, 1000); 

console.log(timer.complete); // complete? false 

    // check the timer object after it has expired 
setTimeout(function() { 
    console.log(timer.complete); // complete? true 
}, 1500); 

编辑:更新到使this在严格模式下一致,并支持传递给回调的附加参数。感谢@Saxoier的提示。

+0

如果您在严格的环境中运行代码(''use strict''),并且使用'this'功能。此外在延迟之后传递参数 - 参数将被忽略。其他参数可能在HTML 5中被标准化 - 已经在Firefox,Chrome和Opera中实现,但可以在不支持它的环境中轻松实现。 [jsFiddle](http://jsfiddle.net/w3p8T/) – Saxoier 2012-01-14 05:59:25

+0

@Saxoier:好点。我更新了。将额外参数直接应用于回调函数而不是'setTimeout',所以参数通常在不受支持的浏览器中运行。 – 2012-01-14 14:08:19

1

是的,这是使用闭包的状态。它非常直接。

要确保你说你是不是一次又一次地调用它,你可以尝试这样的事情......

// declare only once, singleton concept using closure 
(function() { 
    var timerReference, 
    timerMethod = function(fn) { 
     fn(); 
     if (timerReference) { 
      window.clearTimeout(timerReference); 
     } 
     timerReference = window.setTimeout(function() { 
      timerMethod(fn); 
     }, 30000); 
    }; 
    window.doTimer = function(fn) { 
     timerMethod(fn); 
    }; 
})(); 

// you can call this as many times as you like 
doTimer(function() { 
    alert('hi'); 
}); 
doTimer(function() { 
    alert('hi again'); 
}); 

在这种情况下,它调用doTimer()会破坏之前,前一个如此您将一直只有一个计时器。

我也可以编写一个队列,等待最后一个完成,但这是另一个写法。