生成一个密码,每隔n秒检查一次鼠标是否在移动

时间:2019-03-20 07:04:48

标签: javascript jquery

我想创建一个JavaScript函数,每隔n秒调用一次self 因此,如果在移动鼠标时调用此函数,请勿发出ajax请求,否则:进行ajax调用 理论:

function CheckIfMouseIsMoving(){
if(!MouseMoving){
// Make ajax call
}
else{return false;}
}

setInterval(CheckIfMouseIsMoving,3000);

1 个答案:

答案 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)