Created
March 31, 2010 04:56
-
-
Save brentd/349955 to your computer and use it in GitHub Desktop.
delay jQuery's trigger() to prevent queueing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Like jQuery's trigger(), only the firing of the event can be delayed by the | |
// specified duration (in milliseconds). The timer is reset on consecutive | |
// triggers with the same event name, so only the most recent event will be | |
// triggered when the duration ends. Useful if you need to prevent events from | |
// queueing up. | |
// | |
// $('#foo').bind('myEventName', function() {alert('hai')}); | |
// ... | |
// $('#foo').delayedTrigger(1000, 'myEventName', 'event1'); | |
// $('#foo').delayedTrigger(1000, 'myEventName', 'event2'); | |
// $('#foo').delayedTrigger(1000, 'myEventName', 'event3'); | |
// | |
// // Only event3 is triggered after 1 second passes. | |
// | |
$.fn.delayedTrigger = function(duration, eventName, event) { | |
var target = this; | |
var timeoutId = $.delayedEvents[eventName]; | |
if (timeoutId) { | |
clearTimeout(timeoutId); | |
} | |
$.delayedEvents[eventName] = setTimeout(function() { | |
delete $.delayedEvents[eventName]; | |
target.trigger(eventName, event); | |
}, duration); | |
} | |
$.delayedEvents = {}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment