Unable to reset setTimeout timer in JavaScript

Here is my pseudocode:

if(key.pressed = 'a') {
  activate = true;
}

var mytimeout = function timer_function() {
   // Do stuff;
   setTimeout( function() {
    // do more stuff
   }, 5000);
}

function some_function() {
  
 if(activated) {
   // do stuff
   clearTimeout(mytimeout);

   timer_function();
 }
}

if(mouse.click == true) {
  some_function();
}

I want the timer to be reset on each mouse click which calls some_function(). What actually happens is that the time is set on first click but never resets after that.

What am I missing?

Thanks.

>Solution :

mytimeout is a function, not a timeout handle. What you need to store is the result of the setTimeout call like this.

var timeoutHandle;
function timer_function() {
   // Do stuff;
   timeoutHandle = setTimeout( function() {
    // do more stuff
   }, 5000);
}

function some_function() {
  
 if(activated) {
   // do stuff
   clearTimeout(timeoutHandle);

   timer_function();
 }
}

Leave a Reply