Javascript timeout when no actions from user for specified time

后端 未结 7 970
广开言路
广开言路 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:16

    This calls for a debouncer:

    function debounce(callback, timeout, _this) {
        var timer;
        return function(e) {
            var _that = this;
            if (timer)
                clearTimeout(timer);
            timer = setTimeout(function() { 
                callback.call(_this || _that, e);
            }, timeout);
        }
    }
    

    Used like this:

    // we'll attach the function created by "debounce" to each of the target
    // user input events; this function only fires once 2 seconds have passed
    // with no additional input; it can be attached to any number of desired
    // events
    var userAction = debounce(function(e) {
        console.log("silence");
    }, 2000);
    
    document.addEventListener("mousemove", userAction, false);
    document.addEventListener("click", userAction, false);
    document.addEventListener("scroll", userAction, false);
    

    The first user action (mousemove, click, or scroll) kicks off a function (attached to a timer) that resets each time another user action occurs. The primary callback does not fire until the specified amount of time has passed with no actions.

    Note that no global flags or timeout variables are needed. The global scope receives only your debounced callback. Beware of solutions that require maintenance of global state; they're going to be difficult to reason about in the context of a larger application.

    Note also that this solution is entirely general. Beware of solutions that apply only to your extremely narrow use case.

提交回复
热议问题