Skip to content

Instantly share code, notes, and snippets.

@samsalisbury
Created June 13, 2012 16:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samsalisbury/2925113 to your computer and use it in GitHub Desktop.
Save samsalisbury/2925113 to your computer and use it in GitHub Desktop.
JavaScript monadic timeout (jQuery plugin)
// Provides safe way to ensure that you only have a single timeout
// set for a particular event, in the face of browsers not always
// firing the expected events...
// Usage example:
//
// var myTimeout = $.monadicTimeout(function() { doSomething(); }, 500);
//
// $(".some-class").mouseenter(myTimeout.clear);
// $(".some-class").mouseleave(myTimeout.set);
//
// Notes: This was created to solve a common problem with hiding a menu
// after a timed delay on mouseout. If you leave and re-enter the
// menu before the first timeout has fired, you end up with the
// first timeout being fired while the mouse is over the menu,
// hiding it at the wrong time.
(function($) {
$.extend({
monadicTimeout: function(func, period) {
var buffer = [];
function clear() {
while (buffer.length != 0) {
clearTimeout(buffer.shift());
}
}
function set() {
clear();
buffer.push(setTimeout(func, period));
}
return {
clear: clear,
set: set
};
}
});
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment