我正在检查一些遗留代码,我注意到以下几行:
// Stray timeout
var t = setTimeout('',1);
它有什么作用吗?真的需要吗?
SO 上有以下问题:Why is setTimeout(fn, 0) sometimes useful?
The solution is to "pause" the JavaScript execution to let the rendering threads catch up. And this is the effect that setTimeout() with a timeout of 0 does. It is like a thread/process yield in C. Although it seems to say "run this immediately" it actually gives the browser a chance to finish doing some none-JavaScript things that have been waiting to finish before attending to this new piece of JavaScript.
这解释了在 setTimeout 中执行函数的好处。但是执行一个空字符串怎么样?
最佳答案
setTimeout('',1)
这一行什么都不做。您告诉 JavaScript eval()
字符串 ''
。那什么都不做。
有时这样做很有用,因为它“将代码推到堆栈底部”以在函数(以及浏览器正在执行的任何 UI 更新)完成后运行它。
例如:
setTimeout(function(){
// Work with some DOM elements, after the browser has a second to render them
}, 0);
但我看不到空字符串对任何内容有任何影响。
编辑:在 Google Chrome 中,如果您执行 setTimeout('',1)
,它不会返回任何内容。通常,它会向您返回 timeout_id,因此您可以使用 clearTimeout
取消它。但是,在 Google Chrome 中,setTimeout('',1)
返回 undefined
,这让人相信它甚至没有设置超时,因为你没有给它任何事情要做。所以,是的,它字面上什么都不做。
关于javascript - "Stray timeout"- javascript 中的空超时有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23616307/