Executed A Javascript/jquery Function For Some Time, Then Stop
I have 2 javascript function - f1, f2. Ii want to call f2 from f1 in every 2 seconds and i need to do this for 10 minutes. function f1() { //call f1 in every 2 seconds- for 10 m
Solution 1:
You can use a cominbation of setTimeout()
, and setInterval()
like
kill after 10 minutes; 10*60*1000 = 600000 milliseconds
var loop2s = setInterval(function(){
f2();
}, 2000);
// Kill after 10 minutessetTimeout(function(){
clearInterval(loop2s);
},600000);
Solution 2:
You could call f2 from the function itself with a counter. Quick example:
var counter = 0;
functionf1()
{
setTimeout(f2, 2000);
}
functionf2(){
{
counter++;
if (counter < 59) {
setTimeout(f2, 2000);
}
}
Solution 3:
A bit overdone, but was an interesting problem to solve and became a nicer api by returning the stop function instead of using window.clearInterval(someVar);
functionf1(){
// as a test this runs f2 every 400ms for 4 secondsvar stop = interval( f2, 400, 4000 );
// stop() is a function you can call to stop the timer asynchronously
}
functionf2( elapsed ){
console.log('called f2 at ' + elapsed + 'ms' );
}
f1();
/**
* interval
*
* repeat the callback function every n milliseconds, until
* timout or the stop() function is called
*
* @param {Function} cb callback function to perform
* @param {Number} every ms between interval
* @param {Number} timeout timeout for interval
*
* @return {Function} stop stop function to clear the interval
*/functioninterval( cb, every, timeout ){
var start = Date.now(),
timer = null;
timer = window.setInterval(function(){
var elapsed = Date.now() - start;
if( timeout && elapsed > timeout ){
stop();
} else {
cb( elapsed );
}
}, every);
functionstop(){
window.clearInterval( timer );
}
return stop;
}
<scriptsrc="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
Post a Comment for "Executed A Javascript/jquery Function For Some Time, Then Stop"