Jump to content

JavaScript timer


ewannnn

Recommended Posts

Hi I am working on a chat application and am a bit stuck...In the database I have a field status which is set 1 for online and 0 for offline (PHP/MySQL)(at time of logging in/out), this shows the users status on a webpage. What I need is to know if there is a way I can set a timer so that if the user has been inactive for X amount of time, the database is auto updated and user is offline (1 set to 0).

Thanks for any help I recieve  :)

Link to comment
https://forums.phpfreaks.com/topic/218735-javascript-timer/
Share on other sites

 

Exactly what upp said.  The function you want is window.setTimeout.  I'm not sure how your application is set up, but you could set a keydown/keypress listener to reset a timer that will call a function that will set the session as inactive.  Here's a simple example.  Delay is in milliseconds.

 


var timer, delay = 15 * 60 * 1000, active = true;

function makeInactive() {
    active = false;
    // update the server here
}

function keyDownListener() {
    if (timer) clearTimeout(timer);
    if (!active) {
        active = true;
        // update the server here
    }
    timer = setTimeout(makeInactive, delay);
}

keyDownListener(); // start the timer explicitly

// you'll also need to attach the listener to the document.

Link to comment
https://forums.phpfreaks.com/topic/218735-javascript-timer/#findComment-1135524
Share on other sites

Just a thought to add on.

 

You might want to store the "last active time" for each user in the database, and use database functions to see which users should be logged out.

 

This is because users who do not explicitly logout (ie close window/crash) will always be seen as online until they/javascript logs out the next time they visit.

Link to comment
https://forums.phpfreaks.com/topic/218735-javascript-timer/#findComment-1135546
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.