如何在jquery中空闲10秒后执行功能

How to execute function after 10s idle time in jquery?

本文关键字:10秒 执行 功能 jquery      更新时间:2023-09-26

示例:

实际上,如果系统空闲,如何每10秒执行一个功能。

示例:

setInterval(function () {
         test();
         },10000); 
//for every 10 Sec 

如果系统空闲,我正在寻找10。请帮我解决我的问题。

检查document上的mousemovekeyupkeypress事件,并在其中调用您的settimeoutcleartimeout,如下所示:

var interval;
$(document).on('mousemove keyup keypress',function(){
    clearTimeout(interval);//clear it as soon as any event occurs
  //do any process and then call the function again
    settimeout();//call it again
})
function settimeout(){
    interval=setTimeout(function(){
    alert("Idle for 10s"); 
  },10000)
}

DEMO

setInterval是要使用的函数,但如果只在系统空闲时运行,则需要在发生其他事情时重置间隔。

所以你做了:

timeout = setTimeout(function() { test();},10000);

当其他事情发生时,你会进行

clearTimeout(timeout); //clear the timeout
//do stuff;
timeout = setTimeout(function() { test();},10000); //and re-activate it when done

或者更一般地说:

var myVar;
function myFunction() {
    myVar = setTimeout(function(){ test(); }, 3000);
}
function myStopFunction() {
    clearTimeout(myVar);
}

试试这个

setTimeout(function() { test (); }, 10000);

试试这个-在任何您认为有用的事件中调用函数

function test(){      
   // Use your code here...
}
setTimeout(test, 10000);