Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery timeout function to run if a user is inactive

I've got a jQuery timeout script that runs after 30 minutes, however, it is constantly running and I only want it to run if the user has been inactive for that amount of time. How do I go about doing this?

$(function(){
    var timeout = 30000;

    $(document).on("mousemove", function(){
        clearTimeout(timeout);
    })
    setTimeout(function(){
        $.post("../php/logout.php", {}, function(response){
            if(response.success == "1"){
                location.replace("../pages/timed_out.php");
            }
        }, "json");
    }, timeout);
})

1 Answers

You should reset timeout by clearing it using timeout's ID (which can be obtained as setTimeout function result) in clearTimeout and setting timeout again:

$(function()
{
    var timeout = 30000;
    var timer = 0;

    setTimer();

    $(document).on("mousemove", function()
    {
        clearTimeout(timer);
        setTimer();
    });

    function setTimer()
    {
        timer = setTimeout(function()
        {
            $.post("../php/logout.php", {}, function(response)
            {
                if (response.success == "1")
                {
                    location.replace("../pages/timed_out.php");
                }
            }, "json");
        }, timeout);
    }
});
like image 60
Regent Avatar answered May 09 '26 20:05

Regent