简体   繁体   English

我该如何重置设置超时

[英]How can I reset a settimeout

I tried the answer here: Resetting a setTimeout , but it doesn't seem to be working for me. 我在这里尝试了答案: 重置setTimeout ,但它似乎不适用于我。

I'm building a catalog viewer using Owl Carousel. 我正在使用Owl Carousel构建目录查看器。 I have a function set to go off on the afterMove event handler that shows what page the user is on. 我有一个设置为在afterMove事件处理程序上关闭的函数,该事件处理程序显示用户所在的页面。 It displays the page counter and then sets a timeout to have it fadeout after 1 second. 它显示页面计数器,然后设置超时以使其在1秒后淡出。 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 但是window.clearTimeout(timeout)似乎不起作用,我不确定为什么

Thanks 谢谢

var timeout inside the function makes timeout local to the function; 函数内部的var timeout使timeout对于函数而言是局部的; thus, every time you call showCounter , timeout is undefined . 因此,每次调用showCountertimeout都是undefined Move the variable declaration out of the function: 将变量声明移出函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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