我有一个纯 CSS 微调器,我想在 JavaScript 执行其他工作(异步调用,然后迭代大约 10,000 个元素的数组)时显示它。旋转器会在正确的时间出现,但当到达代码中的某个点时就会卡住。在下面的代码中,“一”、“二”和“三”的 console.log
基本上立即发生 - 然后有一个长时间的停顿(当我的旋转器卡住时)然后“四”和“五”一起退出并加载我的内容。所以基本上我知道“console.log('two')
”和“console.log('four')
”之间的代码:
// for search bar
search(text) {
this.searching = true; // shows spinner
console.log('one');
var text = text.toUpperCase();
// search the text with an api call
this.securitiesService.searchSecurities(text)
.subscribe(data => {
var response = data.response;
console.log('two');
// if no search results are present go to correct page
if (!response.length) {
this.router.navigate(...to route...);
return;
}
console.log('three');
// FREEZES HERE !!!
for (var i = 0; i < response.length; i++) {
if (text === response[i].ticker) {
// UNFREEZES HERE !!!
console.log('four');
this.router.navigate(...to route...);
this.searching = false;
console.log('five');
return;
}
}
})
}
我尝试的每个纯 CSS 旋转器都会发生这种情况。
我认为我的 JavaScript 不应该卡住我的纯 CSS 旋转器是错误的吗?为什么代码会卡住它?
最佳答案
JavaScript 在 UI 线程上运行,因此它仍然会阻止纯 CSS 微调器。您需要将工作移出 UI 线程或将其拆分,以便 UI 有时间更新。
根据您需要支持的浏览器,您也许能够使用 Web Workers。请参阅http://caniuse.com/#search=web%20workers浏览器支持或 http://www.html5hacks.com/blog/2012/09/22/web-workers-basics-of-the-web-browsers-ui-thread/例如。
您还可以一次处理一条(或 10 或 100 条)记录,并在 window.setTimeout
或 window.requestAnimationFrame
中调用每个“批处理”。尝试这样的事情(代码未测试):
// for search bar
search(text) {
this.searching = true; // shows spinner
console.log('one');
var text = text.toUpperCase();
// search the text with an api call
this.securitiesService.searchSecurities(text)
.subscribe(data => {
var response = data.response;
console.log('two');
// if no search results are present go to correct page
if (!response.length) {
this.router.navigate(...to route...);
return;
}
console.log('three');
var i = 0;
var self = this;
var processBatch = function () {
if (text === response[i].ticker) {
console.log('four');
self.router.navigate(...to route...);
self.searching = false;
console.log('five');
return;
}
if (++i < response.length) {
window.setTimeout(processBatch, 0);
}
};
window.setTimeout(processBatch, 0);
});
}
如果您想每批处理多个元素,可以在 processBatch
中设置一个循环来迭代少量元素。
旁注:如果 data.response
是字符串,请参阅上面 @gelliott181 的评论。
关于javascript - 纯 CSS 旋转器卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39275894/