Sameeksha Kumari
Sameeksha Kumari

Reputation: 1264

clearInterval on the current element

I am working on a project in which I am dynamically generating many setInterval's, and so it is not possible to store their reference in a variable so that it could be used to clearInterval. Just wanted to ask you guys if anyone has an idea of how to clearInterval on a particular div with an Id.

In my project, when setInterval is supposed to be cleared, I am also removing the element from document body. So when setInterval is called again, I can put a condition to check if the element with that particular id exists and only then I can execute the setInterval code.

Like this,

if(document.getElementById("char0") != null)
{
   // execute the setInterval code. 
}

But this approach will still take CPU time. I am dynamically generating around 150 setIntervals, not possible to create variable reference for them. Please help if you have any clue of how this could be achieved.

Upvotes: 1

Views: 1454

Answers (3)

Neversay
Neversay

Reputation: 81

Try to store the interval variable in a closure:

var createInterval = function(elementId){
    var interval;
    interval = setInterval(function(){
        if(document.getElementById(elementId) == null){
            clearInterval(interval);
        }else{
            //Your code
        }
    },1000);
};

So you can create any number of intervals what you like and remove it when those DOM elements are gone.

createInterval('element1'); 
createInterval('element2');
createInterval('element3');

But as what @alexander-omara said, use only few interval to update all elements is better solution in term of CPU usage.

Upvotes: 2

PM.
PM.

Reputation: 1721

You need to have interval variable to call clearinterval() properly.

If you create variables dynamically like "interval+divid" so each time you get Id, create variable name by this convention and clear the same.

Upvotes: 0

Alexander O'Mara
Alexander O'Mara

Reputation: 60567

You can easily keep a reference to a interval ID on a DOM element:

var element = document.getElementById("char0");
element._someInterval = setInterval(function(){
    //Some code.
}, 1000);

And then clear it using:

if(element._someInterval)
{
    clearInterval(element._someInterval);
}

However, creating hundreds of intervals does not sound like a very efficient means of doing anything. You way want to create 1 interval, and loop over an array of elements.

Upvotes: 1

Related Questions