Skip to content

Instantly share code, notes, and snippets.

@phalkunz
Last active July 12, 2016 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phalkunz/0922a3784c7785e11ff1 to your computer and use it in GitHub Desktop.
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
(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