Question

I would like to know if there is a possible implementation for the following problem in JavaScript:

I want to develop a web application that monitors inactivity for several incoming connections. 10 or more clients would connect to the web app (via WebSockets) causing a 2min timeout timer to start. If a client doesnt make contact with the app for the above internal, its gonna marked as "inactive".

In a more "traditional" language I would've solved the above situation with several threads (one for each client), which would start and fire the timeout timers.

But as far as I can tell JavaScript is single-threaded, so I have no clue where to start..

Was it helpful?

Solution

JavaScript is run client side, so each user would be running the JS locally.

Edit: Jason pointed out in the comments that I missed the Node.js tag you put on the article; thus the above statement is not true for Node.js.

I understand your question to be "How can I have a 2 minute idle check written in JS?". Personally, I'd have a global in your JS code which keeps track of the last time the user performed an action. At the end of each JS function have this variable set with the current Time (More Info Here.). Next, use a JS interval to check that value periodically (More Info Here.).

You would end up with something like this:

var myTime = new Date().getTime();
var timeout = 2 * 60 * 1000;
var interval = 30 * 1000;
window.setInterval(checkTimeout(),interval);

function checkTimeout() {
    var t = new Date().getTime();
    t = t-myTime;
    if (t >= timeout) {
        alert("You've been Idle for 5s+");
    }
    window.setInterval(checkTimeout(),interval);
}
function setTime() {
    myTime = new Date().getTime();
}

Here is an example on jsfiddle.

OTHER TIPS

Create an array for your connections, e.g.:

var connections = [{id: 1, lastActive: ...,}, ...];

Then, use the setTimeout function to check on these periodically:

var interval = 10000; // 10 seconds in milliseconds
var expireTime = 1000 * 60 * 2 // 2 minutes in milliseconds
setTimeout(function() {
  now = new Date()
  for(i = 0; i < connections.length; ++i) {
    if(now - connections[i]['lastActive'] > expireTime) {
      // Do something to make this connection inactive.
    }
  }
}, interval);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top