javascript 延迟关闭窗口javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6788659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
delay closing window javascript
提问by Jerome
I am writing a Google Chrome extension. Thanks to everyone here for putting up with my silly-assed questions. The routine is primitive but runs fine. The only problem is that it runs so fast that it overloads the server and my ip address gets blocked. So it needs a throttle.
我正在编写 Google Chrome 扩展程序。感谢这里的每个人都能忍受我愚蠢的问题。该例程是原始的,但运行良好。唯一的问题是它运行得如此之快,以至于它使服务器过载并且我的 IP 地址被阻止了。所以它需要一个油门。
The question is whether it is better to construct something with a timer or with setInterval. After examining a particular page, the content script closes its window with self.close(). If I put this into a setInterval, I could delay the closing of the page and this would slow the whole process as much as the length of the interval. Seems like a good throttle.
问题是用计时器还是用 setInterval 构造一些东西更好。检查特定页面后,内容脚本使用 self.close() 关闭其窗口。如果我把它放到一个 setInterval 中,我可以延迟页面的关闭,这会像间隔的长度一样减慢整个过程。似乎是一个很好的油门。
Now the last line of the content script is simply:
现在内容脚本的最后一行很简单:
self.close();
I presume that if I modify the code as follows I would get my delay:
我认为如果我修改代码如下,我会得到我的延迟:
var t=setTimeout("self.close()",2000);
Will this work? Is there a better way to do it?
这会奏效吗?有没有更好的方法来做到这一点?
回答by ChristopheCVB
I'd rather use :
我宁愿使用:
setTimeout(function(){
self.close();
},2000);
But your way is valid too...
但你的方式也有效......
回答by Schroedingers Cat
If the closing of the page is an appropriate point to wait, then this is perfectly fine. In this case, because it would appear to be a relevant place, then I think you are fine. Although I would use Christophes suggestion.
如果页面关闭是一个合适的等待点,那么这完全没问题。在这种情况下,因为它看起来是一个相关的地方,所以我认为你很好。虽然我会使用克里斯托夫的建议。
Using a setinterval to run them periodically will run into problems if your processing takes longer than the interval - as this seems to involve opening and closing pages, it could.
如果您的处理时间超过间隔时间,则使用 setinterval 定期运行它们会遇到问题 - 因为这似乎涉及打开和关闭页面,它可能。
As a rule, setInterval is good for doing small processes regularly. In this case, you just want to put a wait into the processing, which suggests to me that setTimeout is better.
通常, setInterval 适合定期执行小流程。在这种情况下,您只想等待处理,这向我表明 setTimeout 更好。