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

setInterval go faster every time it is called

This time go faster if is called 2 times, 3 times faster and so on.

function startIdleTime() {
        var ciclo;

        function startSlidercicle() {
            ciclo = setInterval( function() {
                let seconds = parseInt(sessionStorage.getItem('idle'));
                seconds += 1;
                sessionStorage.setItem('idle', seconds);
            }, 1000);
        }
        // start idle counter
        if (!sessionStorage.getItem('idle')) {
            alert('non esiste timer, lo imposto')
            sessionStorage.setItem('idle', 0);
            alert(3)
        }

        if (sessionStorage.getItem('idle') > 15) {
            anotherFunction();
        }

        if (sessionStorage.getItem('idle') < 15 || !sessionStorage.getItem('idle')) {
            clearInterval(ciclo);
            startSlidercicle();
        }
    }

I need to set idle time. When 15 i'll call an other function,
if <= 15 I reset only a counter to 0
But if is called few times my count go faster then 1sec }, 1000);)

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

>Solution :

Looks like the interval is not cleared before instantiating a new one. The result will be several intervals that will be executed with a different phase, and it will look like it’s running with a shorter interval.

The reason for this behavior is that you are not clearing the interval, because you are creating a new ciclo variable every time you call the startIdleTime function. Probably you want the variable ciclo to be global, in order to share the interval handler across the function calls. You need to widen the scope, and to widen the scope you can just move the variable declaration out of the function definition:

var ciclo;
function startIdleTime() {

        function startSlidercicle() {

Also note that in the following line:

sessionStorage.getItem('idle') < 15 || !sessionStorage.getItem('idle') 

the second part is never evaluated. Let’s suppose that getItem returns null: then null < 15 is true, so the check becomes useless

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