JavaScript Variable setTimeout Loop
Recently I had the need for a function to be repeatedly called for infinity. Normally setInterval
would do the trick, but I wanted the time in between firings to change dynamically.
Here is the solution I came up with.
//global var to change speed
var speedControl = 1;
//use the up/down keys to increase/decrease the speed
//I'm not handling zero here, beware
document.addEventListener('keyup', function(e){
if(e.which == 38){
speedControl++;
console.log(speedControl);
} else if(e.which == 40){
speedControl--;
console.log(speedControl);
}
})
function timer(speedGlobal, cb){
//as the speedControl number rises, the intreval decreases, so speed increases.
var speed = Math.floor(1000/speedGlobal); //cut out nasty decimals
console.log('inside timer', speedGlobal, speed)
//cb is setTimeout
cb(function(){
//call timer recursively, used the global var as the new speedGlobal
timer(speedControl, setTimeout);
}, speed);
}
//start the timer
timer(speedControl, setTimeout);
Currently, this only prints messages to the console. Later I'll show how I use it in a project.
I've been trying to step up my JavaScript game by using closures and functional programming. While I don't really consider this a closure, it does rely on of first class functions since a function is being passed as a parameter. This snippet probably isn't perfect, but it's pretty slick and solved a problem that I had.