我正在尝试编写一个我正在编写的插件,但是我很难找到一个我无法找到解决方案的非常微不足道的问题。我已经找到了几乎每个论坛和相关的问题讨论。这里的任何方式都是我想要发生的,我的插件有一个计时器,我希望用户能够处理它的终止。
(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...
var timer = setInterval(function(){
// Do Something;
},3000);
if(defaults.running == 'false'){
clearInterval(timer);
}
答案 0 :(得分:5)
你真的需要它们能够通过设置变量来停止计时器吗?你可以让他们调用这样的函数吗?
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);
否则,像这样的某些人会起作用:
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);
它使用setTimeout而不是interval,如果running为false,则不会重置超时。
如果您已经设置了使用setInterval,这将解决问题:
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);