Skip to content

Instantly share code, notes, and snippets.

@wizard04wsu
Last active March 16, 2016 19:14
Show Gist options
  • Save wizard04wsu/6c49339709a125b60dfd to your computer and use it in GitHub Desktop.
Save wizard04wsu/6c49339709a125b60dfd to your computer and use it in GitHub Desktop.
Adds a timeout to a callback so that if the function isn't called within the timeout, the callback will be run anyway.
function createFunctionWithTimeout(callback, opt_timeout){
var called, timer;
//if the function *isn't* called within the timeout, execute callback() anyway
timer = setTimeout(function (){
called = true;
callback();
}, opt_timeout || 1000);
//if the function *is* called within the timeout, cancel the timer and execute callback()
return function (){
if(!called){
clearTimeout(timer);
callback();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment