我想创建一个JavaScript函数,每隔n秒调用一次self 因此,如果在移动鼠标时调用此函数,请勿发出ajax请求,否则:进行ajax调用 理论:
function CheckIfMouseIsMoving(){
if(!MouseMoving){
// Make ajax call
}
else{return false;}
}
setInterval(CheckIfMouseIsMoving,3000);
答案 0 :(得分:2)
您可以使用setTimeout()
和document.onmousemove
let MouseMoving = false;
let tm;
document.onmousemove = function(e){
MouseMoving = true;
if(tm) clearTimeout(tm)
tm = setTimeout(() => MouseMoving = false,1000);
}
function CheckIfMouseIsMoving(){
if(!MouseMoving){
console.log("Mousse was not moving")
}
else{
console.log("Mousse was moving")
return false;
}
}
setInterval(CheckIfMouseIsMoving,3000)