Javascript timeout when no actions from user for specified time

后端 未结 7 1007
广开言路
广开言路 2020-12-28 19:32

I want to call a js function when there is no activity from user on the web page for specified amount of time. If there is activity from user then reset timeout. I tried to

7条回答
  •  再見小時候
    2020-12-28 20:24

    Most JavaScript events bubble, so you could do something like the following:

    • Come up with a list of all the events you'd consider to be "activity from the user" (e.g., click, mousemove, keydown, etc.)
    • Attach one function as an event listener for all of those events to document (or maybe document.body for some of them; I can't remember if that's an issue or not).
    • When the listener is triggered, have it reset the timer with clearTimeout/setTimeout

    So you'd end up with something like this:

    var events = ['click', 'mousemove', 'keydown'],
        i = events.length,
        timer,
        delay = 10000,
        logout = function () {
            // do whatever it is you want to do
            // after a period of inactivity
        },
        reset = function () {
            clearTimeout(timer);
            timer = setTimeout(logout, 10000);
        };
    
    while (i) {
        i -= 1;
        document.addEventListener(events[i], reset, false);
    }
    reset();
    

    Note that there are some issues you'd have to work out with the above code:

    • It's not cross-browser compatible. It only uses addEventListener, so it won't work in IE6-8
    • It pollutes the global namespace. It creates a lot of excess variables that might conflict with other scripts.

    It's more to give you an idea of what you could do.

    And now there are four other answers, but I've already typed it all up, so there :P

提交回复
热议问题