Sunday 21 May 2017

Timeout not working

I'm currently working on a site where one user can view a page at a time. I'm using Express JS / Node JS for this.

The idea is: script.js has a function to request a page every second. The server side page has a timer, and if the timer goes above 5s, then a redis key is updated to kick the user off. If the page is requested, then the timer will be set to 0s.

At the moment, the timer works fine with one page but when another page is loaded the timer will not reset to 0.

The site in question is http://leaveamsg.herokuapp.com, which currently has the bug in it, so try it out to see what I mean.

Here is the code:

index.js

...
if(req.query.type == "connectionHeartbeat"){
      client.get("isUserReadingMessage", function(err, reply) {
        if((JSON.parse(reply).userID == req.query.userID) && JSON.parse(reply).response == "yes"){
          client.set("isUserReadingMessage", '{"response": "yes", "userID": "' + req.query.userID + '"}');
          initHBTimer("reset");
          res.send('{"response": "OK", "userID": "' + JSON.parse(reply).userID + '"}');
        } else {
          res.send('{"response": "DENIED"}');
        }
      });

function initHBTimer(status) {
  if(status == "end"){
    iHeart = 5;
  } else if(status == "reset"){
    iHeart = 0;
  } else {
    iHeart = 0;
    onHBTimer();
    function onHBTimer() {
      iHeart++;
      if (iHeart > 4) {
        client.set("isUserReadingMessage", '{"response": "no", "userID": "N/A"}');
      }
      else {
        setTimeout(onHBTimer, 1000);
      }
    }
  }
}
        }

script.js

...
  if(hasSession == false){
    checkForAvailableSlot();
  } else if(hasSession == true){
    $.get("/action?auth=" + authCode + "&type=connectionHeartbeat&userID=" + getCookie("numID"), function(data){
      if(JSON.parse(data).userID != getCookie("numID")){
        endSession('error');
      }
    });
  }
...

hasSession is set to true when the user is viewing the page.

Thanks for the help!

-William



via William G

No comments:

Post a Comment