Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
 }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading