Best way to have an event happen n times?

I am using the following code to create countdowns in Javascript. n is the number of repetitions, frequency is the number of milliseconds to wait before executing, funN is the function to call each iteration (usually a function that updates a portion of the DOM), and funDone is the function to call when the countdown is complete.

function timer(n, freq, funN, funDone)
{
    if(n == 0){
        funDone();
    }else{
        setTimeout(function(){funN(n-1); timer(n-1, freq, funN, funDone);}, freq);      
    }
}

      

It can be called like this:

    timer(10,
      1000, /* 1 second */
      function(n){console.log("(A) Counting: "+n);},
      function() {console.log("(A) Done!");}
     );

    timer(10,
      500,
      function(n){console.log("(B) Counting: "+n);},
      function() {console.log("(B) Done!");}
     );

      

The advantage of this is that I can call timer () as many times as I want without worrying about globals etc. Is there a better way to do this? Is there a clean way to make setInterval stop after a certain number of calls (without using globals)? This code also creates a new lambda function every time setTimeout is called, which seems to be problematic for large countdowns (I'm not sure how the javascript garbage handler does this).

Is there a better way to do this? Thank.

+1


source to share


3 answers


I would create an object that receives a counter and receives a function pointer, something similar to the following pseudo code:

TimedIteration = function(interval, iterations, methodToRun, completedMethod){

  var counter = iterations;
  var timerElapsed = methodToRun;  //Link to timedMethod() method
  var completed = callbackMethod;

  onTimerElapsed = function(){
    if (timerElapsed != null)
      timerElapsed();
  }

  onComplete = function(){
    if (completed != null)
       completed();
  }

  timedMethod = function(){
    if (counter != null)
      if (counter > 0) {
        setTimeOut(interval, onTimerElapsed);
        counter--;
      }
      else
        onComplete();
      this = null;
    }
  }

  if ((counter != null)&&(counter > 0)){
    //Trip the initial iteration...
    setTimeOut(interval, timedMethod);
    counter--;
  }  
}

      

obviously this is pseudo code, I haven't tested it in the IDE and syntactically not sure if it will work like [I would be surprised if there is] but basically what you do you create a wrapper object that receives time interval, number of iterations, and method to start on expired timer.



Then you call this in your method to run like this:

function myMethod(){
  doSomething();
}

function doWhenComplete(){
  doSomethingElse();
}

new TimedIteration(1000, 10, myMethod, doWhenComplete);

      

+2


source


This is basically the same idea as @balabaster, but it's tested, uses a prototype, and has a slightly more flexible interface.



var CountDownTimer = function(callback,n,interval) {
     this.initialize(callback,n,interval);
}

CountDownTimer.prototype = {
     _times : 0,
     _interval: 1000,
     _callback: null,
     constructor: CountDownTimer,
     initialize: function(callback,n,interval) {
                     this._callback = callback;
                     this.setTimes(n);
                     this.setInterval(interval);
                 },
     setTimes: function(n) {
                     if (n)
                         this._times = n
                     else
                         this._times = 0;
                 },
     setInterval: function(interval) {
                     if (interval)
                         this._interval = interval
                     else
                         this._interval = 1000;
                 },
     start: function() {
                     this._handleExpiration(this,this._times);
                 },
     _handleExpiration: function(timer,counter) {
                     if (counter > 0) {
                        if (timer._callback) timer._callback(counter);

                        setTimeout( function() {
                                           timer._handleExpiration(timer,counter-1);
                                          },
                                          timer._interval
                                      );
                     }
                 }
};

var timer = new CountDownTimer(function(i) { alert(i); },10);

...

<input type='button' value='Start Timer' onclick='timer.start();' />

      

+4


source


I like your original solution better than the alternatives suggested, so I just changed it so as not to create a new function for each iteration (and the argument fun()

now has a value before decrementing - change if necessary ...)

function timer(n, delay, fun, callback) {
    setTimeout(
        function() {
            fun(n);
            if(n-- > 0) setTimeout(arguments.callee, delay);
            else if(callback) callback();
        },
        delay);
}

      

+2


source







All Articles