Mark Dibeh
Mark Dibeh

Reputation: 459

generate a scipt to check each n seconds if the mouse is moving

I want to create a javascript function that call it self each n seconds of time so when calling this function if the mouse is mouving do not make ajax request , else : make ajax call theory :

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

setInterval(CheckIfMouseIsMoving,3000);

Upvotes: 0

Views: 40

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36564

You can use setTimeout() and 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)

Upvotes: 2

Related Questions