How to detect idle time in JavaScript elegantly?

前端 未结 30 2450
别跟我提以往
别跟我提以往 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:53

    Pure JavaScript with properly set reset time and bindings via addEventListener

    (function() {
    
      var t,
        timeout = 5000;
    
      function resetTimer() {
        console.log("reset: " + new Date().toLocaleString());
        if (t) { 
          window.clearTimeout(t); 
        }
        t = window.setTimeout(logout, timeout);
      }
    
      function logout() {
        console.log("done: " + new Date().toLocaleString());
      }
      resetTimer();
    
      //And bind the events to call `resetTimer()`
      ["click", "mousemove", "keypress"].forEach(function(name) {
        console.log(name);
        document.addEventListener(name, resetTimer);
      });
    
    }());
    

提交回复
热议问题