Skip to content

Instantly share code, notes, and snippets.

@kolber
Forked from benschwarz/sleep.js
Created August 4, 2010 02:15
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 kolber/507535 to your computer and use it in GitHub Desktop.
Save kolber/507535 to your computer and use it in GitHub Desktop.
/*
Delay function call by a specified time
---------------------------------------------
If the method is called again before the delay is up, reset the delay.
An optional id can be passed to prevent timeout collisions.
*/
Function.prototype.sleep = function(ms, id) {
var id = id || 0;
!window.sleep_delay && (window.sleep_delay = []);
!!window.sleep_delay[id] && clearTimeout(window.sleep_delay[id]);
window.sleep_delay[id] = setTimeout(this, ms, id);
};
/*
Usage
---------------------------------------------
<!DOCTYPE html>
<html lang="en">
<input type="text" name="name1" id="input1">
<input type="text" name="name2" id="input2">
<script src="./sleep.js"></script>
</html>
---------------------------------------------
document.getElementById('input1').onkeyup =
document.getElementById('input2').onkeyup = function() {
(function(id) {
console.log('Finished typing in "'+id+'"');
}).sleep(800, this.id);
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment