How to detect idle time in JavaScript elegantly?

前端 未结 30 2779
别跟我提以往
别跟我提以往 2020-11-21 11:51

Is it possible to detect \"idle\" time in JavaScript?
My primary use case probably would be to pre-fetch or preload content.

Idle time:

30条回答
  •  半阙折子戏
    2020-11-21 12:34

    I use this approach, since you don't need to constantly reset the time when an event fires, instead we just record the time, this generates the idle start point.

               function idle(WAIT_FOR_MINS, cb_isIdle) {
                var self = this, 
                    idle,
                    ms = (WAIT_FOR_MINS || 1) * 60000,
                    lastDigest = new Date(),
                    watch;
                //document.onmousemove = digest;
                document.onkeypress = digest;
                document.onclick = digest;
    
                function digest() {
                   lastDigest = new Date(); 
                }
                // 1000 milisec = 1 sec
                watch = setInterval(function(){
                    if (new Date() - lastDigest > ms && cb_isIdel) {
                        clearInterval(watch);
                        cb_isIdle();
                    }
    
                }, 1000*60);    
            },
    

提交回复
热议问题