Good suggestions John as always. .in() can't be done because 'in' is a
JS keyword and I wouldn't want to have to call it like $()['in']() all
the time. So I figured two JS keywords smashed together would work and
chose .doin() as the function name; if you have any better ideas (maybe
.timeout() and .interval()) let me know.
So this can handle multiple different one-off delays and interval-ed
events. These can then be canceled based on their reference label or
their interval if you didn't provide a label (not both).
Example:
$('p.display')
.doin(500,function() { window.alert("a"); })
.doin(1000,function() { window.alert("b"); })
.doin(500,function() { window.alert("c"); })
.doin(1000,'other',function() { window.alert("d"); })
.doin(500,'other',function() { window.alert("e"); });
// Alerts: 'a','b','c'
$('p.display').stop('other');
// Alerts: 'b','d','e'
$('p.display').stop(500);
// Alerts: 'a','c','d','e'
$('p.display').stop(1000);
// Alerts Nothing
$('p.display').stop();
I'll probably host this on my server if there's any interest. Any Questions?
-blair
Code Below:
jQuery.fn.extend({
every: function(interval,id,fn) {
return this.each(function() {
var self = this;
interval = jQuery.speed(interval);
if (fn == undefined) {
fn = id;
id = interval;
}
if (!this.timers) this.timers = {};
if (!this.timers[id]) this.timers[id] = [];
this.timers[id].push(window.setInterval(function() {
fn.call(self);
},interval));
});
},
doin: function(interval,id,fn) {
return this.each(function() {
var self = this, counter = 0;
interval = jQuery.speed(interval);
if (fn == undefined) {
fn = id;
id = interval;
}
if (!this.timers) this.timers = {};
if (!this.timers[id]) this.timers[id] = [];
this.timers[id].push(window.setInterval(function() {
if (counter++ >= 1) return jQuery(self).stop(id);
fn.call(self);
},interval));
});
},
stop: function(id) {
return this.each(function() {
if (!this.timers) return;
if (id == undefined)
jQuery.each(this.timers, function(i) {
jQuery.each(this,function(j) {
window.clearInterval(this);
});
});
else if (this.timers[id])
jQuery.each(this.timers[id],function(i) {
window.clearInterval(this);
});
});
}
});
John Resig wrote:
> What if you had a trifecta of functions:
> .every()
> .in()
> .stop()
>
> and allow for function calls like this:
>
> .every( 100, "text", function(){
> if ( !$(this).val() )
> $(this).stop("text");
> });
>
> or if you don't care about a name:
>
> .in( "slow", function(){
> $(this).hide();
> })
> .mouseover(function(){
> $(this).stop();
> });
>
> or if you wanna get really interesting, make it so that you can stop
> function calls by how long their timer is set for:
>
> .every( 500, function(){
> $("#foo").load("test.html");
> })
> .every( 100, function(){
> if ( !$(this).val() )
> $(this).stop(100);
> });
>
> Just throwing out some ideas, let me know which ones stick.
_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/