gpt4 book ai didi

javascript - SetTimeout 未返回正确的值且脚本无响应

转载 作者:行者123 更新时间:2023-11-28 13:39:10 26 4
gpt4 key购买 nike

假设我想将一个元素的所有后代的 tagName 放入一个数组中。

var node = document.getElementById('mainbar');

但是,由于我们使用下面的函数循环多个节点,因此我添加了一个 setTimeout 函数,以便在每 50 次循环后使函数超时。

function MyFunction(root){
"use strict";
var myarray = [], descendants, descendant, i=1, l;
descendants = root.getElementsByTagName('*');

function getParentNode(){
for(l = descendants.length; i<l ; i++){
descendant = descendants[i];
myarray.push({ tagName: descendant.tagName});

// After 50 loops, increment i, setTimeout
if(i % 50 == 0 ) {
i++;
setTimeout(getParentNode, 20);
}

}
}

function init(){
getParentNode();
return JSON.stringify({ nodes:myarray });
}

return init();
}

但是,有两个问题:

  1. 不返回完整的数组 (myarray)。
  2. 即使我使用了setTimeout,当过程很长时,屏幕也会卡住。

我该如何解决这些问题?我的意思是我已经使用了 setTimeout,这样页面就不会变得无响应。

P.S.:您可以在 Stackoverflow 本身上测试该脚本,因为它包含一个 id mainbar 的元素。 我同意获取标记名不会花费这么长时间,但我还在计算其他一些事情,例如每个元素的过滤 getComputedStyle,这肯定需要相当长的时间。我把这个问题作为概念证明,以了解如何使用 setTimeout 来阻止脚本响应

最佳答案

忽略其他人提到的所有其他问题,只回答如何完成异步功能的问题。您可以在代码中引入回调的想法。您不必尝试在调用后立即使用结果,而是传递一个在结果准备好后调用的函数:

http://jsfiddle.net/4CdJ2/

function MyFunction(root, callback) {

/* ... */

function getParentNode() {
for (l = descendants.length; i < l; i++) {

/* ... */

if (i % 50 == 0) {
i++;
setTimeout(getParentNode, 20);
return;
}
}

// made it out of the loop, must be done
var result = JSON.stringify({
nodes: myarray
});

callback(result);
}

getParentNode();
}

var result = MyFunction(document.getElementById("root"), function(result){
alert("GOT RESULT: " + result);
});

关于javascript - SetTimeout 未返回正确的值且脚本无响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19183166/

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