gpt4 book ai didi

javascript - 创建不带 while 的 JavaScript 循环

转载 作者:行者123 更新时间:2023-11-28 12:08:44 25 4
gpt4 key购买 nike

我正在尝试创建一个需要执行大量循环的页面。使用 while/for 循环会导致页面挂起,直到循环完成,在这种情况下,循环可能会运行几个小时。我也尝试过使用 setTimeout,但这达到了递归限制。如何防止页面达到递归限制?

var looper = {
characters: 'abcdefghijklmnopqrstuvwxyz',
current: [0],
target: '',
max: 25,
setHash: function(hash) {
this.target = hash;
this.max = this.characters.length;
},
getString: function() {
string = '';
for (letter in this.current) {
string += this.characters[this.current[letter]];
}
return string;
},
hash: function() {
return Sha1.hash(this.getString());
},
increment: function() {
this.current[0] += 1;
if (this.current[0] > this.max) {
if (this.current.length == 1) {
this.current = [0, 0];
} else {
this.current[1] += 1;
this.current[0] = 0;
}
}
if (this.current[1] > this.max) {
if (this.current.length == 2) {
this.current[2] == 0;
} else {
this.current[3] += 1;
this.current[2] = 0;
}
}
},

loop: function() {
if (this.hash() == this.target) {
alert(this.getString());
} else {
this.increment();
setTimeout(this.loop(), 1);
}
}
}

最佳答案

setInterval 是通常的方法,但您也可以尝试 Web Worker,这将是比 setInterval 更直接的代码重构,但仅适用于 HTML5 浏览器。

http://dev.w3.org/html5/workers/

关于javascript - 创建不带 while 的 JavaScript 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6462480/

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