Maria Jane Maria Jane - 1 year ago 49
Javascript Question

ClearInterval function doesn't work in my case

function active_timer(){
var time = 5000;

interval = setInterval(function(){


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?

Answer Source

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);


// button click to simulate your socket event
$('#simulate').on('click', function() {
  console.log('received simulated event');
<script src=""></script>
<button id="simulate">Simulate Socket Event</button>