简体   繁体   中英

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

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! ...
  // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM