How to detect idle time in JavaScript elegantly?

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

    Here is a rough jQuery implementation of tvanfosson's idea:

    $(document).ready(function(){
    
       idleTime = 0;
    
       //Increment the idle time counter every second.
       var idleInterval = setInterval(timerIncrement, 1000);
    
       function timerIncrement()
       {
         idleTime++;
         if (idleTime > 2)
         {
           doPreload();
         }
       }
    
       //Zero the idle timer on mouse movement.
       $(this).mousemove(function(e){
          idleTime = 0;
       });
    
       function doPreload()
       {
         //Preload images, etc.
       }
    
    })
    

提交回复
热议问题