Jack Pilowsky
Jack Pilowsky

Reputation: 2303

How can I reset a settimeout

I tried the answer here: Resetting a setTimeout, but it doesn't seem to be working for me.

I'm building a catalog viewer using Owl Carousel. I have a function set to go off on the afterMove event handler that shows what page the user is on. It displays the page counter and then sets a timeout to have it fadeout after 1 second. Probably is lots of people go through pages faster than once per second. So, I need to reset the timeout if the function gets called again.

function showCounter(){
     var $counter = $('#counter');
     //clear timeout
     window.clearTimeout(timeout);
     //Display counter
     $counter.show();
     //set timeout
     var timeout = window.setTimeout(function(){
         $counter.fadeOut(500);
     }, 1000);
}

But window.clearTimeout(timeout) doesn't seem to be working and I'm not sure why

Thanks

Upvotes: 0

Views: 216

Answers (1)

Amadan
Amadan

Reputation: 198566

var timeout inside the function makes timeout local to the function; thus, every time you call showCounter, timeout is undefined. Move the variable declaration out of the function:

var timeout;
function showCounter() {
  // ...
  timeout = // NO VAR! ...
  // ...
}

Upvotes: 2

Related Questions