Skip to content

Instantly share code, notes, and snippets.

@luckyshot
Created October 31, 2013 14:16
Show Gist options
  • Save luckyshot/7250551 to your computer and use it in GitHub Desktop.
Save luckyshot/7250551 to your computer and use it in GitHub Desktop.
Run only once every X seconds (timer)
/**
* This version uses Date to detect cooldown
* Much better performance than with Timer
*/
var cooldownTime = 2000, // ms
nextRun = null;
function run() {
// Your code here
console.log( 'Run my stuff! ' + Date.now() );
}
function clicked() {
var now = +new Date; // IE8 compatibility http://afuchs.tumblr.com/post/23550124774/date-now-in-ie8
if (!nextRun || nextRun <= now) {
nextRun = now + cooldownTime;
run();
}
}
document.addEventListener('click', clicked);
/**
* This version uses a Timer
* It is recommended to use the Date version instead
*/
var COOLDOWN_TIME = 2000, // ms
wait = false,
t;
function runner() {
// Your code here
console.log( 'Run my stuff! ' + Math.random(100) );
}
function cooler() {
if (wait === false) {
runner();
t = setTimeout(function(){
wait = false;
}, COOLDOWN_TIME);
}
wait = true;
}
document.addEventListener('click', cooler);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment