问题
So I'm making an image slider and I'd like to be able to clearInterval() on my autoplay timer from within my init function where I've placed my click event handler for the pagination module. I want to do this so when the user clicks on a dot during autoplay it doesn't break the image rotation. The problem is that the timer functionality is within my play function which is not within my init function. See below:
function Plugin( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.item = 0;
this.init();
}
Plugin.prototype = {
init: function() {
var base = this;
if ( this.options.legend === "on" ) {
html = "<div id='legend'/>";
$(this.element).append(this.generateLegend(this.options.images)).find(".img-number").click(function(){
// store index of currently active image
base.item = $("#img-container").children(".active").index();
// only animate if the new index is different from the current
if ( base.item !== $(this).index() ) {
// call animation effect
base.move(base.item, $(this).index());
// add active class to selected index and remove any previous active classes from other indices
base.updateIndex("#legend", $(this).index());
base.updateIndex("#img-container", $(this).index());
}
}).wrapAll(html);
if ( this.options.autoplay === "on" ) {
base.play();
}
return this;
},
updateIndex: function(el, index) {
$(el).children().eq(index).addClass("active").siblings().removeClass("active");
},
play: function() {
var base = this;
setInterval(function() {
if ( base.item === base.options.images.length-1 ) {
base.updateIndex("#img-container", 0);
base.updateIndex("#legend", 0);
base.move(base.item, 0);
base.item = 0;
}
else {
base.updateIndex("#img-container", base.item+1);
base.updateIndex("#legend", base.item+1);
base.move(base.item, base.item+1);
base.item += 1;
}
}, base.options.pduration);
},
// animation effect for changing image indices
move: function(cur, dest) {
$("#img-container > img").animate({
"right": "+=" + 100 * (dest-cur) + "%"
}, this.options.aduration, this.options.easing);
}
};
I'm trying to write this plugin without "cheating" by looking at how other sliders do it. I want to do it my way, but also properly.
回答1:
Just save the interval in the base
var: this.intervalTimer = window.setInterval( ... );
and access it where ever you want.
回答2:
setInterval()
and setTimeout()
both return an integer which can be used with clearTimeout()
and clearInterval()
, which is used to cancel intervals/timeouts.
Saved the returned integer in your object instance and cancel the interval/timeout when user interaction is detected.
来源:https://stackoverflow.com/questions/17769665/clearinterval-on-image-slider-plugin