Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am using

varName = setInterval(function() { ... }, 1000);

to set a couple of intervals in a jquery plugin that I'm writing, but when the plugin is reloaded I need to clear those intervals. I tried storing them in variables, like this:

(function($){
$.mosaicSlider = function(el) {
    var base = this;        
    var transitionInterval, mainInterval;

...

base.init = function() {
    mainInterval = setInverval(function() { ... }, 1000);
}

base.grid = function() {
    this.transition() = function() {
         transitionInterval = setInterval(function(...) {
    }
}

base.init();

And I tried killing those intervals in the base.init() function, like this:

clearInterval(transitionInterval);
clearInterval(mainInterval);

And like this:

window.oldSetInterval = window.setInterval;
window.setInterval = new function(func, interval) {  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
213 views
Welcome To Ask or Share your Answers For Others

1 Answer

Store 'em in an object. Since you're the only one making these intervals, and you know what they are, you can store them and later mess with them as you wish. I'd create an object dedicated for just that, something like:

var interval = {
    // to keep a reference to all the intervals
    intervals : new Set(),
    
    // create another interval
    make(...args) {
        var newInterval = setInterval(...args);
        this.intervals.add(newInterval);
        return newInterval;
    },

    // clear a single interval
    clear(id) {
        this.intervals.delete(id);
        return clearInterval(id);
    },

    // clear all intervals
    clearAll() {
        for (var id of this.intervals) {
            this.clear(id);
        }
    }
};

Your first question might be

Why make a separate object for just that?

Well Watson, it's to keep your hand-made intervals related to your plugin/project away from prying eyes, so you won't mess with other intervals being set in the page not related to your plugin.

Yes, but why can't I store it inside the base object?

You most certainly can, but I think this way is much cleaner. It separates the logic you do in your base with the weird timeout logic.

Why did you store the intervals inside a Set and not an array?

Faster access and a little bit of cleaner code. You can go either way, really.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...