setInterval handle is a string and not a number in raspbian

46 views Asked by At

I'm trying to clear a setInterval by getting the handle or ID, but setInterval is returning a long string. Here is my code:

io.sockets.on('connection', function (client) {
  var myInterval;
  client.on('gettemp', function(data) {
      myInterval = setInterval(function(){
          getTemperature(client);
      }, 2000);
      console.log(myInterval);
  });
  client.on('stopread', function(data) {
      clearInterval(myInterval);
});

When this is executed and I log myInterval which should be an integer, I get for myInterval in the console.log(myInterval):

Timeout {
  _called: false,
  _idleTimeout: 2000,
  _idlePrev:
   TimersList {
     _idleNext: [Circular],
     _idlePrev: [Circular],
     _timer: Timer { '0': [Function: listOnTimeout], _list: [Circular] },
     _unrefed: false,
     msecs: 2000 },
  _idleNext:
   TimersList {
     _idleNext: [Circular],
     _idlePrev: [Circular],
     _timer: Timer { '0': [Function: listOnTimeout], _list: [Circular] },
     _unrefed: false,
     msecs: 2000 },
  _idleStart: 14937,
  _onTimeout: [Function],
  _timerArgs: undefined,
  _repeat: 2000 }

What is going on here? setInterval is working by emitting a temperature every 2000 milliseconds in the getTemperature(client) function, but I can't stop it because I can't get the handle for clearInterval(myInterval) because myInterval is a long string. Of course I can stop it with ^C with SSH where I start the node temperature.js application but I can't stop it with a button in the index.html file.

1

There are 1 answers

0
Steve.e On

Thanks for your help. I see now that this is working fine. My confusion was that the first console log in gettemp was different from the console log in stopread so I assumed it wasn't working. I found that myInterval was being updated every time setInterval timed out. Strange that it would do this without the gettemp service being called again, I only call it once. I put the console log in the callback and saw a different myInterval every time it timed out. The stopread saw the correct myInterval. I assume it might miss if the asynchronous timing was just right.

Your last comment about repeated execution pointed out that any client could stop the service which I don't necessarily want. I'll put the setInterval in the client and have it request a gettemp from the service.