如何在Javascript中执行不会阻塞UI的循环? [英] How to do a loop in Javascript that doesn't block the UI?
问题描述
我的页面上有一些JavaScript,执行时间很长(介于10到30秒之间)
I have some javascript on my page that takes a very long time to execute (between 10-30 seconds)
代码基本上看起来像这样:
The code basically look like that :
//Iterate over all the elements in the array
for(int i=0; i<array.length; i++){
//Complex stuff for each element
}
问题在于,在执行此代码时,UI没有响应.
The problem is that while this code is executing, the UI is not responsive.
有什么办法可以解决这个问题?我知道javascript具有某种异步性,但我以前从未真正使用过它.
Is there any way to solve this issue? I know javascript has some sort of asynchrony but I never really used it before...
此外,元素的处理顺序必须始终是它们在数组中出现的顺序.
Also, the order the elements are processed must always be the order that they appear in the array.
编辑:我使用setTimeout()和重复"尝试了以下解决方案,但仍然无法解决我的问题.我想这是因为数组的大小不是很大,但是每个元素的计算都很大.
EDIT : I tried the solution below with setTimeout() and in the "duplicate", but it still doesn't fix my problem. I guess it's because the size of my array is not very big BUT the calculation for each element is pretty big.
我想要响应的UI也是一个动画加载gif.由于每个项目的计算量太大,因此动画很草率.
Also the UI I want to be responsive is an animated loading gif. Since the calculation for each item is too big, the animation is sloppy.
推荐答案
创建一个变量并将其设置为计数器的起始值.
Create a variable and set it to the starting value for your counter.
创建一个函数,该函数:
Create a function that:
- 执行循环主体所做的任何事情
- 增加计数器
- 测试以查看计数器是否仍在该长度以下,如果是,则再次调用该函数
此时,您将具有与已经拥有的功能相同的功能.
At this point you will have functionality equivalent to what you have already.
要在每次调用该函数之间暂停并留出时间触发其他函数,请使用对 setTimeout
的调用替换对函数的直接调用,并将该函数用作第一个参数./p>
To pause between each call of the function, and allow time for other functions to fire, replace the direct call to the function with a call to setTimeout
and use the function as the first argument.
var counter = 0;
function iterator () {
//Complex stuff for each element
counter++;
if (counter < array.length) {
setTimeout(iterator, 5);
}
}
这篇关于如何在Javascript中执行不会阻塞UI的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!