正如@Parth 指出的那样,浏览器在单个线程中运行 javascript,因此,如果<div>
不存在覆盖,UI 事件将被触发,但将保留在队列中,直到长时间运行的功能完成。但是,通常不会出现这种行为。如果要冻结 UI,只需保留<div>
叠加层。
如果你想让浏览器有机会更新 UI(或允许用户取消处理),你必须将长时间运行的函数逻辑分解为各种函数调用,并使用window.setTimeout calls
. 有几种方法可以实现这种模式,但我喜欢非递归封闭队列方法:
// this will block UI until all images are painted:
function paintAll(arImg) {
for(var i=0; i<arImg.length; i++) paintSingle(arImg[i]);
}
// this will block UI only while each image is painted:
function paintAll(arImg) {
// copy arImg to queue not to modify the input parameter
var queue = arImg.slice(0);
// apply the paint function to the first element, remove it from queue
// and set the runner function to run again after 5 milliseconds
// (this will allow the UI thread to run between each runner call)
var runner = function() {
// check any UI based condition to abort running:
if(!checkUiBasedCondition()) return;
if(!queue.length) return;
paintSingle(queue.shift());
window.setTimeout(runner, 5);
}
// call runner to initiate the processing
runner();
}
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/shift
https://developer.mozilla.org/en/DOM/window.setTimeout