Created
June 13, 2012 16:31
-
-
Save samsalisbury/2925113 to your computer and use it in GitHub Desktop.
JavaScript monadic timeout (jQuery plugin)
This file contains 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
// 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