最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reset setTimeout() back to maximum time without executing? - Stack Overflow

programmeradmin1浏览0评论

I am setting a timeout ex:

button.onClick(
 timer = setTimeout(func(){}, 1000);
);

When the button is clicked again, I want to set timer back to 1000 without it running func().

As is, multiple clicks of the button just make the timer go off at some random time. I've tried calling clearTimeout(timer) before, but it does nothing.

I've run into this problem before several times where I just want to reset the timer on the trigger event, and have always had to end up finding a workaround. I can't imagine there is no way to just put the timer back to maximum. Any insight without writing my own version of setTimeout from scratch is greatly appreciated.

I am setting a timeout ex:

button.onClick(
 timer = setTimeout(func(){}, 1000);
);

When the button is clicked again, I want to set timer back to 1000 without it running func().

As is, multiple clicks of the button just make the timer go off at some random time. I've tried calling clearTimeout(timer) before, but it does nothing.

I've run into this problem before several times where I just want to reset the timer on the trigger event, and have always had to end up finding a workaround. I can't imagine there is no way to just put the timer back to maximum. Any insight without writing my own version of setTimeout from scratch is greatly appreciated.

Share Improve this question asked May 3, 2017 at 4:26 verstehe_verstehe_ 981 silver badge7 bronze badges 1
  • 1 so you want to remove the previous timer and reset its time to 1000ms? – madalinivascu Commented May 3, 2017 at 4:31
Add a ment  | 

2 Answers 2

Reset to default 5

Set the timer as a global variable, clear the previous timer on click

var timer;
button.onClick(
    clearTimeout(timer);
    timer = setTimeout(func(){}, 1000);
);
button.onClick(
    clearTimeout(timer);
    timer = setTimeout(func(){}, 1000);
);

See https://developer.mozilla/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout

发布评论

评论列表(0)

  1. 暂无评论