node.jscleartimeout

node.js clearTimeout() not working


I try to build an alert function which fires after 5 Min if my garagedoor is still open. The problem ist that no matter what message comes after "offen" the cleartimeout is not working, so the Alert is executed after every "offen"status. would be great if someone can give me a hint...

    function handleGarageState(message) {
      Status = message.toString();
      garageState = message
      io.emit('Garagenstatus', {
        data: String(garageState)
      });
      var Eintrag = {
        Datum: moment().format('YYYY-MM-DD HH:mm:ss'),
        Status: Status
      };
      writeStatus(Eintrag);
      if (Status == 'offen') {
       var alert = setTimeout(function () {
          console.log("ALERT "); //here will be the alert function
        }, 60000 * 5)
      } else {
        clearTimeout(alert);
      }
    }

Solution

  • function handleGarageState(message) {
        Status = message.toString();
        garageState = message;
        io.emit('Garagenstatus', {
            data: String(garageState)
        });
        var Eintrag = {
            Datum: moment().format('YYYY-MM-DD HH:mm:ss'),
            Status: Status
        };
        writeStatus(Eintrag);
        if (Status == 'offen') {
            //v-- Here
            var alert = setTimeout(function () {
                console.log("ALERT "); //here will be the alert function
            }, 60000 * 5)
        } else {
            clearTimeout(alert);
        }
    }
    

    You are creating a new var alert on each call to that function. Problem is, the old alert is still waiting somewhere. You need to centralize alert outside the scope of the function and clear it before putting a new timeout.

    var alert;
    
    function handleGarageState(message) {
        Status = message.toString();
        garageState = message;
        io.emit('Garagenstatus', {
            data: String(garageState)
        });
        var Eintrag = {
            Datum: moment().format('YYYY-MM-DD HH:mm:ss'),
            Status: Status
        };
        writeStatus(Eintrag);
        if (Status == 'offen') {
            clearTimeout(alert);
            alert = setTimeout(function () {
                console.log("ALERT "); //here will be the alert function
            }, 60000 * 5)
        } else {
            clearTimeout(alert);
        }
    }