Ahmet Ömer
Ahmet Ömer

Reputation: 644

How to run a function 1 minute after the mousemove event?

I want to run a function after the last mousemove event. I've tried the code below:

@HostListener('document:mousemove', ['event'])
   eventHandler(event) {
    setTimeout(() => {
     // do something
    }, 60000);
   }

The problem is, it fires in the first mousemove event and won't reset the time if another event occurs. How to reset it and start the setTimeout function each time the event occurs?

Upvotes: 0

Views: 803

Answers (2)

Adrian Pop
Adrian Pop

Reputation: 1967

Well, when you call setTimeout, the return value is a number, representing the ID value of the timer that is set. Use this value with the clearTimeout() method to cancel the timer and set it again when a new event occurs. You can read more about setTimeout and clearTimeout here and here.

Basically you can have something like:

//global variable
var timeoutID;

[...]

@HostListener('document:mousemove', ['event'])
   eventHandler(event) {
    if (timeoutID)
        clearTimeout(timeoutID);

    timeoutID = setTimeout(() => {
     // do something
    }, 60000);
}

I provided a simple jsfiddle (pure js, no framework) too:

var timeoutValue = 2000;
var timeoutID;

document.addEventListener("mousemove", function() {
  if (timeoutID)
    clearTimeout(timeoutID);

  timeoutID = setTimeout(function() {
      console.log(timeoutValue + " just passed");
  }, 2000);
});

Cheers!

Upvotes: 1

Jamiec
Jamiec

Reputation: 136144

I'm not sure which framework you're using, but in general you need to store the Id of the timer and cancel it every time and start a new one - remembering to capture the Id.

var timerId = 0

document.addEventListener("mousemove",function(){
  clearTimeout(timerId);
  timerId = setTimeout(function(){
      console.log("5 seconds since last mouse move");
  },5000);
});

Upvotes: 3

Related Questions