Javascript timeout when no actions from user for specified time

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

    Something like this:

    function onInactive(ms, cb){   
    
        var wait = setTimeout(cb, ms); 
    
        // Bind all events you consider as activity
        // Note that binding this way overrides any previous events bound the same wa
        // So if you already have events bound to document, use AddEventListener and AttachEvent instead
        document.onmousemove = document.mousedown = document.mouseup = document.onkeydown = document.onkeyup = document.focus = function(){
            clearTimeout(wait);
            wait = setTimeout(cb, ms);
    
        };
    
    }
    

    IE: http://jsfiddle.net/acNfy/ Activity in the bottom right frame will delay the callback.

    0 讨论(0)
提交回复
热议问题