title: Set and Clear Timeout on Node Server from Client
body: <p>I'm attempting to allow a user to set an alarm from the client and pass it to the server. The server then has a setTimeout that counts down and when time runs out, executes the function.</p>
  
  <p>This first part is working fine, however, I need the the ability to clear that same timeout, should the client decide to cancel that particular alarm.</p>
  
  <p>Note: I've been storing various data using Redis, so that is available.</p>
  
  <pre><code>var client = redis.createClient();
  io.set("store", new sio.RedisStore);
  
  io.sockets.on('connection', function (socket) {
  
  socket.on('alarm:config', function(list, date, time, bool) {
  
    if (bool) {
  
      var now = new Date().getTime();
  
      var year = date[0],
          month = date[1] - 1,
          day = date[2];
  
      var hour = time[0],
          minutes = time[1];
  
      var alarm = new Date(year, month, day, hour, minutes);
  
      var countdown = alarm - now;
  
      var myAlarm = setTimeout(function() {
  
        // do stuff...
  
      }, ( countdown ) );
  
    } else {
  
      clearTimeout(myAlarm);
  
    }
  
  });
  });
  </code></pre>
  
  <p>The approach I have in mind is that I would use the boolean value to determine if the user is setting or canceling that particular alarm. <strong>I realize that setting a local variable "myAlarm" will not work, I just put it there to convey the idea.</strong></p>
  
  <p>I am trying to figure out a way to store a reference to that exact timeout so that the next time the "alarm:config" socket event is triggered with a false boolean value, it can cancel the timeout that was set earlier.</p>
  
  <p>It might be another question all together, but how does an application like Google Calendar store a date and time and then know exactly when to trigger it as well as offer the ability to cancel it? This would essentially be the same idea.</p>
  
  <p><strong>UPDATE: I have it working using the following solution. I am open to a more elegant solution.</strong></p>
  
  <pre><code>socket.on('alarm:config', function(list, date, time, bool) {
  
    var alarmName = "timer:" + list;
  
    if (bool) {
  
      client.hset(alarmName, "status", true);
  
      var now = new Date().getTime();
  
      var year = date[0],
          month = date[1] - 1,
          day = date[2];
  
      var hour = time[0],
          minutes = time[1];
  
      var alarm = new Date(year, month, day, hour, minutes);
  
      var countdown = alarm - now;
  
      setTimeout(function() {
  
        client.hget(alarmName, "status", function(err, bool) {
  
          if(bool == 'true') {
  
            // do stuff...
  
          } else {
  
            console.log("This alarm has been canceled.");
  
          }
  
        });
  
      }, ( countdown ) );
  
    } else {
  
      console.log('canceling alarm');
      client.hset(alarmName, "status", false);
  
    }
  });
  </code></pre>