Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create dynamically variable for setInterval?

I create a hmtl page with node and ejs with an unforseeable number of elements. I would like to create a setInterval for some, none or all of those elements, depending what the user is doing.

The problem is, that I am not able to create a dynamically variable for the setInterval so that I can later on cancel those Intervals.

Maybe I just need another simpler approach but at the moment I am stuck here.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

camContainer.forEach(element => {
        clearInterval(intervalVar);
        if (!element.classList.contains("hidden")) {
            countVisible++;
            intervalVar = setInterval(showConsole, 1500);
        } else {
            countHidden ++;
        }
    count++;    
    })

I tried it with an Array instead of a regular variable but that didnt work either

intervalVar[count] = setInterval(showConsole, 1500);

>Solution :

You’re on the right track with an array, but you need to push items onto it:

intervalVar = []

// ...

intervalVar.push(setInterval(showConsole, 1500))

When you want to cancel an interval, remove it from the array with slice or pop, depending on how you’re selecting the item to cancel.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading