I have created a jquery plugin with following structure:
(function($){
var timer_handle, i = 5 ;
$.my_plugin = function(){
return{
// provide $.my_plugin.reset() public method to reset
reset : function(){ clearTimeout(timer_handle); }
}
}();
$.fn.my_plugin = function(){
// init codes ...
function tick(){
i -= 1;
console.log(i+'sec elapsed');
if(i == 0){
console.log('time over');
$.my_plugin.reset();
}
timer_handle = setTimeout(tick, 1000);
}
tick();
}
})(jQuery);
$('body').my_plugin();
When I see at console , after 0 sec elapsed, the counter is still running in negative,
ie the setTimeout has not been cleared.
As I examined , the public method
$.my_plugin.reset(); called from outside clear the timer,
but $.my_plugin.reset() called inside tick closure do not clear timer.
What may be the solution for such case ?????
Because you’re calling
$.my_plugin.reset();from inside thetick()function there is no timeout to clear. The previously scheduled timeout has already happened and that’s whytick()is executing. (This has nothing to do with whether the code is in a closure or not.)Instead, just don’t set the next timeout if
ihas reached0:If you were to call
$.my_plugin.reset();from some other code outsidetick()then there would be an outstanding timeout that could be cleared so it would stoptick()running again.Note that declaring your
timer_handleandivariables in that immediately invoked anonymous function means that all calls to your plugin will access those same variables so you will get incorrect behaviour if you run your plugin against more than one element on the page at the same time.