CaatjuhNL1
CaatjuhNL1

Reputation: 11

Resetting a setTimeout using addEventListener Javascript

i am trying to make a function that when clicking your mouse, can see that you are active or AFK. When the time runs out, this person must be offline. If the person clicks again after the time runs out, the person must come back online. Furthermore, the time must always be reset if he clicks again within the time so you can see that he is active on the page. Does anyone know what I need to adjust here to make it work?

var time; 

window.addEventListener('click', function() {
  time = setTimeout(function() { 
    SaveUrl('Save/SetIsOnlineUser', { isOnline: false }); 
  }, 20000);
})

window.addEventListener("click", myFunction);

function myFunction() {
  clearTimeout(time)
  SaveUrl('Save/SetIsOnlineUser', { isOnline: true });
}

Upvotes: 1

Views: 203

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337580

Your logic is flawed as you run opposing logic under two handlers which run under the same event.

To fix this you instead need to use a single event handler. You can set the user online immediately within the click handler, then set the timeout for N seconds later to mark them as offline, something like this:

var time;

window.addEventListener('click', function() {
  clearTimeout(time)
  SaveUrl('Save/SetIsOnlineUser', {
    isOnline: true
  });
  
  time = setTimeout(function() {
    SaveUrl('Save/SetIsOnlineUser', {
      isOnline: false
    });
  }, 5000);
})

function SaveUrl(u, o) {
  console.log('Online:', o.isOnline);
}

Note that I made the timer only 5 seconds to make the effect more obvious.

Upvotes: 1

Related Questions