Stop setInterval within jQuery plugin
I am trying to wrap up a plugin that I am writing but am stumped on a very trivial problem that I cant seem to find a solution for. I have tracked down almost every forum and related problem discussion. Any ways here is what I want to happen, my plugin has a timer that I would like the user to be able to handle its termination.
(function ($) {
...
var defaults = {
callback : function(){},
crossfadeTime : 1000,
easing : 'linear',
running : 'true', // Here is where I would like the user to send a parameter
// to invoke a different result. i.e. 'false' => clearing
// the timer. Such as...
v开发者_如何学Pythonar timer = setInterval(function(){
// Do Something;
},3000);
if(defaults.running == 'false'){
clearInterval(timer);
}
Do you really need them to be able to stop the timer by setting a variable? Could you do it by letting them call a function like this?
var TimerModule = (function(){
var timerHandle;
var startTimer = function(fnc, interval){
if(timerHandle){
//error, timer already running
return;
}
timerHandle = window.setInterval(fnc, interval);
};
var stopTimer = function(){
window.clearInterval(timerHandle);
timerHandle = null;
};
return {
start:startTimer,
stop:stopTimer
};
}());
TimerModule.start(function(){
alert("Hieee");
}, 1000);
window.setTimeout(function(){
TimerModule.stop();
}, 5000);
Otherwise, somethign like this would work:
var defaults = {
callback: function() {
alert("hi");
},
crossfadeTime: 1000,
easing: 'linear',
running: 'true' // Here is where I would like the user to send a parameter
// to invoke a different result. i.e. 'false' => clearing
// the timer. Such as...
};
var timer;
var timerFunction = function() {
if (!defaults.running) {
return;
}
defaults.callback();
timer = setTimeout(timerFunction, 1000);
};
//start the timer
timerFunction();
window.setTimeout(function() {
defaults.running = false;
},5000);
It uses setTimeout instead of interval, and doesn't reset the timeout if running is false.
If you're dead set on using setInterval, this will do the trick:
var defaults = {
callback: function() {
alert("hi");
},
crossfadeTime: 1000,
easing: 'linear',
running: 'true',
callbackHandle: null
};
var timer;
var timerFunction = function() {
if (!defaults.running) {
window.clearInterval(defaults.callbackHandle);
defaults.callbackHandle = null;
}
defaults.callback();
};
//start the timer
defaults.callbackHandle = window.setInterval(timerFunction,1000);
window.setTimeout(function() {
defaults.running = false;
},5000);
精彩评论