user3357400
user3357400

Reputation: 407

start function every 2 seconds and another every 5 seconds

I have function below stats_check(), which sets and clears timer of function stats(). But problem is that this function runs every 2 seconds and if conditions are true it sets timer and start stats(). But I want to check this every 2 seconds, but start function stats() only every 5 seconds. How can I do this?

$(function stats_check() {
    var sections = document.getElementsByTagName("section");
    window.setInterval(function() {
        for (i=0; i<sections.length; i++) {
            if (sections[i].className == "present") {
                if (sections[i].id.match(/^stats-.*$/)) {
                    timer = setInterval(function(){stats()}, 5000);
                }
                else {
                    clearInterval(timer);
                }
            }
        }
    }, 2000);
});

Upvotes: 0

Views: 104

Answers (1)

Andrei
Andrei

Reputation: 3106

You could do it like this:

$(function stats_check(){
    var shouldRunTimer = false,
        sections = document.getElementsByTagName("section");
    window.setInterval(function(){
        for(var i=0; i<sections.length; i++) {
            if(sections[i].className === "present") {
                shouldRunTimer = sections[i].id.match(/^stats-.*$/);
            }
        }
    },2000);

    var timer = setInterval(function(){
        if(shouldRunTimer)
            stats();
    }, 5000);
});

function stats(){
    console.log("runs stats");
}

As seen in this fiddle it works: http://jsfiddle.net/D669N/

What this does is:

  • set 2 second timer where you check the conditions
  • if the conditions are true, allow the stats function to run, else do not allow it
  • set a 5 seconds timer where you check if you are allowed to run the stats function

Also I did some corrections to your code:

  • added var to the i in the for-loop. If you don't add var it will go in global-scope and that is bad and could create bugs that are really hard to debug.

  • used === instead of == to compare the className because in this scenario it is better than ==.

You can read more about those 2 last observations in other answers on stackoverflow, there are a lot of them.

Upvotes: 1

Related Questions