简体   繁体   中英

ClearInterval function doesn't work in my case

function active_timer(){
    var time = 5000;

    interval = setInterval(function(){
        console.log('interval');
    },time);
}

active_timer();

socket.on('timer', function (data) {

    console.log('here') // it triggered

    clearInterval(interval); // don't work
    active_timer() //resume
});

I tried this and it won't work because the console.log still triggered every 5 sec. Any clue why?

Your code is technically running correctly but your console logs are misleading.

You've started an interval which triggers every 5 seconds. Each time your socket even fires, you clear the interval but then immediately start a new one. This gives the illusion that there's no gap in the intervals, but there is.

You can test this by changing your console.log('interval') to console.log(interval) . So instead of just printing "interval", it will print out the value of the variable referencing the interval object. This is represented by a number which will change each time the interval is stopped and restarted.

Just to be clear, an interval cannot be resumed , only new ones started and existing ones stopped.

 var interval = null; function startTimer() { // store the reference to our interval interval = setInterval(function() { console.log('triggered interval', interval); }, 2000); console.log('new interval started', interval); } startTimer(); // button click to simulate your socket event $('#simulate').on('click', function() { console.log('received simulated event'); clearInterval(interval); startTimer(); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="simulate">Simulate Socket Event</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM