gpt4 book ai didi

javascript - 纯 CSS 微调器卡住

转载 作者:行者123 更新时间:2023-11-30 09:44:51 26 4
gpt4 key购买 nike

我有一个纯 CSS 微调器,我想在我的 JavaScript 执行其他工作时显示它(一个异步调用,然后迭代一个包含大约 10,000 个元素的数组)。微调器会在正确的时间出现,但会在代码中的某个特定点被点击时卡住。在下面的代码中,'one'、'two' 和 'three' 的 console.logs 基本上立即发生 - 然后有一个很长的停顿(当我的微调器卡住时)然后“四”和“五”一起注销,我的内容加载了。所以基本上我知道“console.log('three')”和“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-only 微调器。您需要将工作移出 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.setTimeoutwindow.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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com