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>