Is there a way to check of clearTimeout was successful.
I have a javascript function which is run at an interval of 30 seconds asynchronously. It is a self calling function and uses setTimeout() to repeat itself in a loop. In a particular case, I need to call this function after some event occurs. Hence I first clearTimeout and call the function again. But I don't know whether I was able to successfully clear the previous loop or have I started two separate loops now. Can I do something like this? :
if(clearTimeout(timer))
alert("cleared");
"Is there a way to check of clearTimeout was successful."
No, there's no state maintained that you can check, but if you manage your timers properly, it shouldn't be an issue.
You could create your own stateful timer object I suppose...
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);
};
Example of clearing the 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
Example of letting it run...
// 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);
EDIT: Updated to make this
consistent in strict mode, and to support additional argument passed through to the callback. Thanks to @Saxoier for the note.
Yes, this is state using a closure. Its quite straight forward.
To ensure you are not calling it again and again as you say, you can try something like this...
// 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');
});
In this case it calling doTimer() will destroy the previous one before it so you will always have only one timer going at one time.
I can also code one that will queue them up and wait for the last one to complete but that is another writeup.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With