Created
March 14, 2012 14:01
-
-
Save real34/2036665 to your computer and use it in GitHub Desktop.
Javascript : DelayedCall - prevent a callback to be triggered before a delay of inactivity
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
/** | |
* Class allowing to call a method only after a specific delay if no other call was made | |
* It is useful to prevent triggering the same callback multiple times quickly. For instance | |
* ajax calls on keyup. It introduces a delay before triggering the callback | |
* | |
* Usage: | |
* var refreshResults = new DelayedCall(1000, function() { alert('Mouse not moved for 1 second'); }) | |
* $('body').mousemove(function() { refreshResults.trigger(); }) | |
* | |
* @param delay Inactivity delay in millisecond before triggering the callback | |
* @param callback Callback to trigger after a specific delay | |
* @return void | |
*/ | |
function DelayedCall(delay, callback) { | |
this.delay = delay; | |
this.callback = callback; | |
this.timeout = null; | |
this.trigger = function() { | |
window.clearTimeout(this.timeout); | |
this.timeout = setTimeout(this.callback, this.delay); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment