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

how to set a timeout to infinity in javascript - Stack Overflow

programmeradmin2浏览0评论

I have a timeout event that I want to set to infinity. Right now I just set it to 9999999 meaning that after that many milliseconds the event will trigger. But it is not so elegant, what's a better way to make it infinite?

I have a timeout event that I want to set to infinity. Right now I just set it to 9999999 meaning that after that many milliseconds the event will trigger. But it is not so elegant, what's a better way to make it infinite?

Share Improve this question asked Jan 13, 2020 at 7:11 mhamha 6472 gold badges12 silver badges24 bronze badges 4
  • 11 Why do you need to do this? If you don't want the event to ever fire, don't schedule it in the first place. – Barmar Commented Jan 13, 2020 at 7:13
  • 1 setTimeout accepts only 32 bit integers so you cannot have a threshold more than 2^31 -1 i.e. 2,147,483,647 – arizafar Commented Jan 13, 2020 at 7:16
  • @Barmar Say you have a function which returns a promise but you need timeout functionality as well, then you may do like timeoutFetch(url, timeout = 2147483647){ return new Promise((v,x) => (setTimeout(_ => x("fetch timed out"), timeout), v(fetch(url))));};. So 2147483647 is the default timeout argument value which takes effect if it is not provided like timeoutFetch(url,200) but timeoutFetch(url). – Redu Commented Mar 7, 2021 at 17:29
  • 1 @Redu you could just do if (timeout) setTimeout(...), as suggested in the answer. – Barmar Commented Mar 7, 2021 at 17:35
Add a ment  | 

1 Answer 1

Reset to default 5

There is no reason to trigger event after infinity time. Doing that will make events stays in stack forever and they could pile up.

Correct approach:

function triggerThisOnSomeEvent() {
    let isEventExecutable = CONDITIONS_THAT_SET_THIS_TO_TRUE_OR_FALSE;
    if (isEventExecutable) {
        // Handle event
    }
}
发布评论

评论列表(0)

  1. 暂无评论