Last active
July 12, 2016 04:50
-
-
Save phalkunz/0922a3784c7785e11ff1 to your computer and use it in GitHub Desktop.
Make sure a callback won't run more than once during a specified duration
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
(function() { | |
var __timerIDs = {}; | |
/** | |
* Make sure the callback won't run more than once | |
* during a specified duration. | |
* | |
* This function relies on variable __timerIDs | |
* in outer scope. | |
* | |
* Usage: | |
* | |
* ``js | |
* threshold('foo', function() { ... }, 500); | |
* `` | |
* | |
* @param string - name to identify the task/callback | |
* @param function | |
* @param integer - duration in millisecond (default is 100) | |
*/ | |
var threshold = function(name, callback, duration) { | |
duration = duration || 100; | |
// If the callback has been queue to run | |
if(__timerIDs.hasOwnProperty(name)) { | |
clearTimeout(__timerIDs[name]); | |
} | |
// Queue to callback to run | |
__timerIDs[name] = setTimeout(function() { | |
callback(); | |
clearTimeout(__timerIDs[name]); | |
}, duration); | |
}; | |
window.threshold = threshold; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment