I have already tried all the methods, I can not stop the timer on the nodejs server. Tried different options with setInterval and setTimeout. I always get a working timer.

function myTimer(room,step){ holand.get(room, function(err, reply) { console.log(reply); var newcena = reply - step; console.log('New price '+newcena); holand.set(room, newcena); socket.emit('iscena', newcena.toFixed(2)); }); } var timerId; console.log('1 '+timerId); socket.on('howcena', function(data){ var room = data.room; var step = data.step; console.log(room); console.log(step); timerId = setTimeout(function tick() { myTimer(room,step); timerId = setTimeout(tick, 5000); }, 5000); console.log('2 '+timerId); }); socket.on('stopcena',function(data){ clearTimeout(timerId); console.log('3 '+timerId); console.log('Stop timer'); }); 
  • Which of the two timers can you stop? - Dmytryk
  • @ Dmytryk It is necessary to stop both timers, there is no fundamental difference, in cases with setInterval I tried to stop but did not work, maybe in cases with setTimeout I’m not trying to do it right? - Dmitry Papava

1 answer 1

 var timerId; function myTimer(room,step){ holand.get(room, function(err, reply) { console.log(reply); var newcena = reply - step; console.log('New price '+newcena); holand.set(room, newcena); socket.emit('iscena', newcena.toFixed(2)); }); } function tick() { myTimer(room,step); if (timerId) { timerId = setTimeout(tick, 5000); } } console.log('1 '+timerId); socket.on('howcena', ({ room, step }) => { console.log(room); console.log(step); timerId = setTimeout(tick, 5000); console.log('2 '+timerId); }); socket.on('stopcena', () => { clearTimeout(timerId); timerId = null; console.log('3 '+timerId); console.log('Stop timer'); }); 

The problem is that clearTimeout will stop the timer only after the last execution of the function, in which there is no condition blocking the start of the next timer. The solution is to write some condition so as not to start the timer.