0

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 minutes
}

function f2(){
{

}

How can i implement this in javascript/jquery or how to use Settimeout, setInterval for the above scenario.

0

3 Answers 3

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  minutes
setTimeout(function(){

   clearInterval(loop2s);

},600000);
Sign up to request clarification or add additional context in comments.

Comments

1

You could call f2 from the function itself with a counter. Quick example:

var counter = 0;    
function f1()
{
    setTimeout(f2, 2000);
}

function f2(){
{
    counter++;
    if (counter < 59) {
        setTimeout(f2, 2000);
    }
}

Comments

0

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);

function f1(){
  // as a test this runs f2 every 400ms for 4 seconds
  var stop = interval( f2, 400, 4000 );
  // stop() is a function you can call to stop the timer asynchronously
}

function f2( 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
 */
function interval( 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);
  
  function stop(){
    window.clearInterval( timer );
  }
  
  return stop;
}
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.