Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Variable as Time in setInterval / setTimeout [duplicate]

Here is an example situation.

var count,
    time = 1000;

setInterval(function(){
    count += 1;
}, time);

The code above will add 1 to the "count" var, very 1000 milliseconds. It seems that setInterval, when triggered, will use the time it sees on execution. If that value is later updated it will not take this into account and will continue to fire with the initial time that was set.

How can I dynamically change the time for this Method?

like image 956
Panomosh Avatar asked Sep 23 '13 15:09

Panomosh


1 Answers

Use setTimeout instead with a callback and a variable instead of number.

function timeout() {
    setTimeout(function () {
        count += 1;
        console.log(count);
        timeout();
    }, time);
};
timeout();

Demo here

Shorter version would be:

function periodicall() {
    count++;
    setTimeout(periodicall, time);
};
periodicall();
like image 75
Sergio Avatar answered Sep 25 '22 03:09

Sergio