1

I am running this JS code in my Browser Console to display some names from a table in an interval of 4 seconds. After the loop has run X amount of times, it should clear the interval.

$(document).ready(function() {
    for(var j = 0; j < 2; j++) {
        var refreshIntervalId = setInterval(function(){var td = $("tr td:first-child");
            for (var i = 6; i < 26; i++){
                console.log(td[i].innerText);
            }},4000);
        $("#idc4").click();
    }
    clearInterval(refreshIntervalId);
});

I've saved the interval ID in the variable refreshIntervalId and I am calling the clearInterval function after the loop with this ID, but my interval keeps running, displaying the same names in the console. Is the variable out of scope? Or does the browser console have some limitations when it comes to this?

Leth
  • 1,033
  • 3
  • 15
  • 40

1 Answers1

0

You need your intervals to stop themselves after they've been called X times.

So you'll need to change your code's logic a little. Because right now, your for loop combined with the use of var will replace your intervalId each time you loop.

I introduced an intervalContext object that contains the intervalId and the number of times it was called. By binding it to the interval, each interval has its own intervalContext.

// how many times will the interval be called :
var numberOfCalls = 3;

for (var j = 0; j < 2; j++) {
    // initiating a new intervalContext
    var intervalContext = {};    
    intervalContext.called = 0;
    // storing the intervalId in the intervalContext so the interval can clear itself 
    intervalContext.intervalId = setInterval((function() {
        // the intervalContext object will be referenced by 'this'
        this.called++;

        for (var i = 6; i < 26; i++) {
            console.log("looping i = " + i);
        }

        if (this.called > numberOfCalls) {
            console.log("Interval cleared. ID=", this.intervalId);
            clearInterval(this.intervalId);
        }
    }).bind(intervalContext), 1000); // binding the interval to the intervalContext
    console.log("Interval started. ID=" + intervalContext.intervalId);

}
Guillaume Georges
  • 3,878
  • 3
  • 14
  • 32