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 run and stop multiple Intervels in Javascript

Suppose i am calling 3 interval with time 500ms,1s,1.5s. once i click on 500ms button that time i need to stop other 2 interval run only 500ms. Like i click on 1s then stop previous interval that is 500ms. How i figure it out.

socket.on("interval-1",(value)=>{
        console.log(value);
        if(value==1){
           
            var timer1  = setInterval(function(){
                let price = Math.floor(Math.random() * 100);
                socket.emit("price",price)
               
            },500);
            
        }
        
        else if(value==2){
           
           var timer2  = setInterval(function(){
                clearInterval(timer1)
                let price = Math.floor(Math.random() * 100);
                socket.emit("price",price)
                
            },1000);
        }
        else if(value==3){
          
            setInterval(function(){
                clearInterval(timer1)
                clearInterval(timer2)
                let price = Math.floor(Math.random() * 100);
                socket.emit("price",price)
                
            },1500);
        }
        
    })

I tried it but once i interval it started it is not stoping when i click on run other intervals.

Thanks in Advance!

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 :

Your timer1 and timer2 variables are local to one execution of the socket.on() handle so when a subsequent handler comes, you can’t access the previous variables. You can fix this by declaring the timer variables at a higher scope so the same variable is accessible on subsequent socket.io messages. I’d suggest an implementation like this:

let previousTimer;

socket.on("interval-1", (value) => {
    console.log(value);
    // clear any previous interval timer so it doesn't keep going forever
    if (previousTimer) {
        clearInterval(previousTimer);
        previousTimer = null;
    }
    if (value == 1) {
        previousTimer = setInterval(function () {
            let price = Math.floor(Math.random() * 100);
            socket.emit("price", price)
        }, 500);
    } else if (value == 2) {
        previousTimer = setInterval(function () {
            let price = Math.floor(Math.random() * 100);
            socket.emit("price", price)
        }, 1000);
    } else if (value == 3) {
        previousTimer = setInterval(function () {
            let price = Math.floor(Math.random() * 100);
            socket.emit("price", price)
        }, 1500);
    }
});

Notes: The variable I declared called previousTimer in this implementation is a module-level variable, not a global variable. It is accessible only to the code within this module.

Also, you should stop using var. Modern Javascript should use let or const, not var.

You also generally want to use === for comparisons, not ==. If the value variable is actually a number, not a string, then you should use === to compare it. The comparison with == will attempt to do type conversion, allowing a number to be equal to a string which can lead to very unpredictable results in your code.

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