使用setTimeout来提高响应能力 [英] Using setTimeout to improve responsiveness
问题描述
在寻求改善页面性能时,我之前没有提到的一种技术是使用setTimeout来阻止javascript阻止页面的呈现。
When looking to improve a page's performance, one technique I haven't heard mentioned before is using setTimeout to prevent javascript from holding up the rendering of a page.
例如,假设我们有一个特别耗时的jQuery内嵌html:
For example, imagine we have a particularly time-consuming piece of jQuery inline with the html:
$('input').click(function () {
// Do stuff
});
如果此代码是内联的,我们将阻止感知完成当jquery忙于将点击处理程序附加到页面上的每个输入时页面。
If this code is inline, we are holding up the perceived completion of the page while the piece of jquery is busy attaching a click handler to every input on the page.
生成新线程是否明智:
setTimeout(function() {
$('input').click(function () {
// Do stuff
})
}, 100);
我能看到的唯一缺点是用户现在更有可能点击元素单击处理程序已附加。但是,这种风险可能是可以接受的,即使没有setTimeout,我们也有一定程度的风险。
The only downside I can see is that there is now a greater chance the user clicks on an element before the click handler is attached. However, this risk may be acceptable and we have a degree of this risk anyway, even without setTimeout.
我是对的,还是我错了?
Am I right, or am I wrong?
推荐答案
实际技术是使用时间为0的 setTimeout
。
The actual technique is to use setTimeout
with a time of 0.
这是因为JavaScript是单线程的。超时不会导致浏览器生成另一个线程,也不保证代码将在指定的时间内执行。但是,代码将在以下两个时间执行:
This works because JavaScript is single-threaded. A timeout doesn't cause the browser to spawn another thread, nor does it guarantee that the code will execute in the specified time. However, the code will be executed when both:
- 指定的时间已过。
- 执行控制权交还给浏览器。
因此,用时间调用 setTimeout
0可以被认为是临时屈服于浏览器。
Therefore calling setTimeout
with a time of 0 can be considered as temporarily yielding to the browser.
这意味着如果你有长时间运行的代码,你可以通过定期屈服<$ c来模拟多线程$ C>的setTimeout 。您的代码可能如下所示:
This means if you have long running code, you can simulate multi-threading by regularly yielding with a setTimeout
. Your code may look something like this:
var batches = [...]; // Some array
var currentBatch = 0;
// Start long-running code, whenever browser is ready
setTimeout(doBatch, 0);
function doBatch() {
if (currentBatch < batches.length) {
// Do stuff with batches[currentBatch]
currentBatch++;
setTimeout(doBatch, 0);
}
}
注意:虽然在某些情况中了解此技术很有用,但我非常怀疑您是否需要它在你描述的情况下(在DOM上准备事件处理程序)。如果性能确实是一个问题,我建议通过调整选择器来寻找改善真实性能的方法。
Note: While it's useful to know this technique in some scenarios, I highly doubt you will need it in the situation you describe (assigning event handlers on DOM ready). If performance is indeed an issue, I would suggest looking into ways of improving the real performance by tweaking the selector.
例如,如果你只是在页面上有一个表单,其中包含< input>
s,然后给< form>
一个ID,并使用 $('#someId input')
。
For example if you only have one form on the page which contains <input>
s, then give the <form>
an ID, and use $('#someId input')
.
这篇关于使用setTimeout来提高响应能力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!