我正在努力使代码在多个元素中同时运行,而不是依次执行。
有关代码功能的背景知识:
此代码一个接一个地遍历每个元素。我试图使其运行,所以它同时执行。
function mover() {
paras = Array.from(document.querySelectorAll('.working1'));
jobelement = document.getElementById("jobend");
for (const para of paras) {
if (para.innerHTML) {
machinetext = para.textContent;
var words = machinetext.split(' ');
var mySubString = words[3].substring(
words[3].lastIndexOf(" ") + 1,
words[3].lastIndexOf(",")
);
times = mySubString * 100;
setTimeout(function() {
jobelement.innerHTML = machinetext;
console.log(mySubString);
para.textContent = "";
mover();
}, times);
break;
}
}
}
mover();
<p id="machine1" class="working1">Job No.78 (Cost, 62, C)</p>
<p id="machine2" class="working1">Job No.68 (Cost, 67, B)</p>
<p id="machine3" class="working1">Job No.68 (Cost, 93, A)</p>
<p id="machine4" class="working1">Job No.68 (Cost, 45, C)</p>
<p>------------------------------<p>
<p id="jobend" class="jobends"></p>
我希望首先执行最低的延迟,然后再执行第二最低的延迟,依此类推。 目前的实际结果是,首先完成第一个元素,然后完成第二个元素,然后是第3个,然后是第4个。
答案 0 :(得分:0)
您快到了,您只需要删除setTimeout
回调内部的递归调用即可(该回调仅根据元素的顺序而不是时间延迟来链接元素),也请删除break
因为它使for
循环变得无用,并使用let
在循环内声明变量,所以您不会得到这个issue(这样每个元素都会有自己的延迟数字和所有元素的数字都不相同):
for (const para of paras) {
if (para.innerHTML) {
machinetext = para.textContent;
let words = machinetext.split(' ');
let mySubString = words[3].substring( // use let here (important)
words[3].lastIndexOf(" ") + 1,
words[3].lastIndexOf(",")
);
times = mySubString * 100;
setTimeout(function() {
jobelement.innerHTML = machinetext;
console.log(mySubString);
para.textContent = "";
// remove the recursive call to mover()
}, times);
// remove break
}
}
工作示例:
function mover() {
paras = Array.from(document.querySelectorAll('.working1'));
jobelement = document.getElementById("jobend");
for (const para of paras) {
if (para.innerHTML) {
machinetext = para.textContent;
let words = machinetext.split(' ');
let mySubString = words[3].substring(
words[3].lastIndexOf(" ") + 1,
words[3].lastIndexOf(",")
);
times = mySubString * 100;
setTimeout(function() {
jobelement.innerHTML = machinetext;
console.log(mySubString);
para.textContent = "";
}, times);
}
}
}
mover();
<p id="machine1" class="working1">Job No.78 (Cost, 62, C)</p>
<p id="machine2" class="working1">Job No.68 (Cost, 67, B)</p>
<p id="machine3" class="working1">Job No.68 (Cost, 93, A)</p>
<p id="machine4" class="working1">Job No.68 (Cost, 45, C)</p>
<p>------------------------------<p>
<p id="jobend" class="jobends"></p>