简体   繁体   English

JavaScript 函数 setTimeout() 和 setInterval() 有时不起作用

[英]JavaScript functions setTimeout() and setInterval() are sometimes not working

My own Google Chrome extension stops working after some time, because setTimeout() is not working in some cases.我自己的 Google Chrome 扩展在一段时间后停止工作,因为 setTimeout() 在某些情况下不起作用。

Therefore the background script is not sending a message to the content script after some necessary delay.因此,在一些必要的延迟之后,后台脚本不会向内容脚本发送消息。

I have found this problem by writing many console.log() statements.我通过编写许多 console.log() 语句发现了这个问题。

As a solution i thought about using setInterval() until the message is sent to the content script:作为一种解决方案,我考虑使用 setInterval() 直到将消息发送到内容脚本:

var timer = setInterval(function() {
  clearInterval(timer);
  // Sending a message to the content script
}, 3000);

My code before, during and after setInterval() is quiet long, so i hope this code snippet is somehow enough.我在 setInterval() 之前、期间和之后的代码很长,所以我希望这段代码足够了。

Does anyone know in which cases these Timeouts or Intervals do not start?有谁知道在哪些情况下这些超时或间隔不会启动?

Or are there any similar options i could use?或者我可以使用任何类似的选项吗?

I have thought about using the Chrome Alarms API instead, but alarms can only be used once every minute and the minimum delay is one minute if i am not mistaken.我曾考虑过使用 Chrome 闹钟 API,但闹钟每分钟只能使用一次,如果我没记错的话,最短延迟是一分钟。

I never experienced any issue of setinterval or settimeout stops working.我从未遇到过任何 setinterval 或 settimeout 停止工作的问题。 I guess there might be an issue in your code.我猜你的代码可能有问题。 If you are sure about the bug you should make a demo project and report bug on github.如果您确定该错误,您应该制作一个演示项目并在 github 上报告错误。

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

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