Last active
December 19, 2015 07:29
-
-
Save ElfhirDev/5919168 to your computer and use it in GitHub Desktop.
JavaScript setInterval "interval" parameter cannot be changed during runtime. Maybe there are other solutions using more params (not supported in I.E 7 and below) for setInterval (but we can add a polyfill I have seen). I have adapted and add comment to the solution of Peter Bailey (14/08/09) :
http://stackoverflow.com/questions/1280263/changing…
This file contains hidden or 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
var intervals = [2,3,4,5]; | |
var index = 0; | |
/** | |
* Custom "setInterval" with internal function modifying the interval | |
* | |
* @param callback The function to call various times | |
* intervals A duration using seconds | |
* index | |
* | |
*/ | |
function setCustomTimer( callback, intervals, index ) { | |
var internalCallback = function( t, counter ) { | |
return function() { | |
// Call our internal callback routine with different interval of time | |
window.setTimeout( internalCallback, 1000 * intervals[index] ); | |
// We don't care of the internal routine, that's the callback we really want :) | |
callback(); | |
// The index will loop the fixed-size array again and again ; not tested with a filling array | |
index++; | |
if(index > intervals.length) { | |
index = 0; | |
} | |
} | |
}( intervals, 0 ); | |
window.setTimeout( internalCallback, intervals ); | |
}; | |
setCustomTimer( function(){ | |
// Call here any routine function | |
console.log( 'bye' ); | |
}, intervals, index ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment