Created
October 31, 2013 14:16
-
-
Save luckyshot/7250551 to your computer and use it in GitHub Desktop.
Run only once every X seconds (timer)
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
/** | |
* 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 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
/** | |
* 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