I have the following jQuery extension:
var particleTimer = 0;
jQuery.fn.particleEmitter = function (num, wid, hei, rad, tme, rep) {
particleTimer = setInterval(function() {
//appends elements...
}, 500);
};
jQuery.stopParticleEmitter = function () {
clearInterval(particleTimer); //this doesn't stop it...
}
But the clearInterval() doesn’t seem to work…
Here is a Fiddle of my complete code: http://jsfiddle.net/neuroflux/wtJFj/3/
Note that the “particles” won’t actually move as it requires the document width…
But the timer should clear onMouseout… and doesn’t…
In terms of the actual
setInterval, your code looks fine and I can’t see any reason that it wouldn’t work provided you only hever have one particle emitter running at any given time.I say that bit about “one at a time” because the first thing that jumped out at me is that you’re assuming no one using your plug-in will ever call your
particleEmittermore than once, because you’re using a single variable for the handle.I’d make maintaining that handle the caller’s responsibility by returning it rather than keeping track of it yourself.
Returning the handle out of the
particleEmittermeans you can’t chain, but A) Your original didn’t support chaining (barring needing to return anything else, convention is to returnthisout of plug-in functions, for chaining); and B) One doesn’t always need to support chaining, not if you have a good reason for returning a different value.Side-note: I returned
0out of the stopper function above because I tend to use this idiom in my code:Obviously, that style may not be to your taste. 🙂
Live working example of two emitters with the caller keeping track of the handles:
HTML:
JavaScript:
Update: You asked below about stopping them all. That’s easily done, just keep track of the handles you hand out (live example):
Note how all of this is wrapped in a function, so the
handlesvariable is private to our plug-in.