"Is there a way to verify clearTimeout was successful."
No, there is no state that you can check, but if you manage your timers correctly, this should not be a problem.
You can 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 a 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
Run permission example ...
// 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 the optional argument passed to the callback. Thanks @Saxoier for the note.
user1106925
source share