Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a function a specified number of times

Tags:

javascript

function runAgain()
{
    window.setTimeout(foo, 100);
}

function foo()
{
    //Do somthing
    runAgain();
}

I can use the above code to run a function infinite number of times with an interval of one second.

What is the standard way of running a function defined number of times. Lets say, I want foo() to be run 5 times with an interval of 1 second.

EDIT It's said that global variables should be avoided in Javascript. Isn't there a better way?

With input from answers, I created a function like this: (Working Example: http://jsbin.com/upasem/edit#javascript,html )

var foo = function() {
    console.log(new Date().getTime());  
};


var handler = function(count) {
    var caller = arguments.callee;
    //Infinite
    if (count == -1) {
        window.setTimeout(function() {
            foo();
            caller(count);
        }, 1000);
    }
    if (count > 0) {
        if (count == 0) return;
        foo();
        window.setTimeout(function() {
            caller(count - 1);
        }, 100);    
    }
    if (count == null) {foo(); }
};

handler(-1); //Runs infinite number of times
handler(0); //Does nothing
handler(2); //Runs two times
handler(); //Runs foo() one time
like image 805
yetanotherstacker Avatar asked Mar 25 '12 09:03

yetanotherstacker


2 Answers

var counter = 1;
function foo()
{
    if (counter < 5){
        counter++
        window.setTimeout(foo, 1000);
    }
}

foo()// it will run 5 times;

LIVE DEMO


Version with "static variable":

function foo() {
    if (typeof foo.counter == 'undefined') {
        foo.counter = 0;
    }
    alert("Run No. " + (++foo.counter));

    if (foo.counter < 5) {
        setTimeout(function() {
            foo(foo.counter + 1);
        }, 400);
    }    
}

foo();

LIVE DEMO


Version with hidden input

function foo() {
    var counter = document.getElementById('counter');
    var counterValue = parseInt(counter.value, 10);
    alert('Run No. ' + counterValue);
    if (counterValue< 5) {
        counter.value = counterValue + 1;
        window.setTimeout(foo, 400);
    }
}

foo();​

LIVE DEMO


Version with closure :

var x = function() {
    var counter = 1;

    (function foo() {
        alert('Run No. ' + counter);

        if (counter < 5) {
            counter++;
            setTimeout(foo, 400);
        }
    })();
};
x();​

LIVE DEMO

like image 129
gdoron is supporting Monica Avatar answered Sep 22 '22 01:09

gdoron is supporting Monica


use a global variable and increment it in the function foo() to count the number of times it has been called.

var counter=0;
function runAgain()
{
    window.setTimeout(foo, 1000);
}

function foo()
{        
    //Do somthing
    if((++counter)<5)
    runAgain();
}
like image 27
Yash Gupta Avatar answered Sep 22 '22 01:09

Yash Gupta