[英]How to make for loop wait for an element before moving to next iteration
I have a for loop with an array of xpaths which selects button elements and selects an option in a select box. 我有一个带有xpaths数组的for循环,该数组选择按钮元素并在选择框中选择一个选项。 This should happen one by one for each array item. 对于每个数组项,应该逐个发生。 The code I have works more or less but doesn't wait for the option element if element is null. 我拥有的代码或多或少都可以工作,但是如果element为null,它不会等待option元素。 I want the for loop to try finding the element until it is found before executing the rest of the code in the for loop and moving to next iteration. 我希望for循环尝试查找元素,直到找到为止,然后再在for循环中执行其余代码并移至下一次迭代。
case = ["xpath1", "xpath2", "xpath3", "xpath4"];
function loopThroughArray(case) {
for (var i = 0; i <case.length; i++) {
(function(i) {
setTimeout(function() {
//start - getting the corresponding elements and clicking it
var dt_links = document.evaluate(case[i], document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var dtLinks = dt_links.snapshotLength;
if (dtLinks != 0) {
for (var a = 0; a < dtLinks; ++a) {
dt_links.snapshotItem(a).click();
}
var ex = document.evaluate("//select/optgroup/option[contains(text(),'new item')]", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var expEl = ex.snapshotItem(0);
if (expEl == null) {
console.log("new item option is not available");
}
else{
//"new item" option is selected
ex.snapshotItem(0).selected = true
var exp = $('select')[2] //select box
console.log(exp)
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
exp.dispatchEvent(evt);
} else {
exp.fireEvent("onchange");
console.log("change event to be fired");
}
}
}
}, 1500 * i);
})(i);
};
}
loopThroughArray(case);
so basically, I need to iterate over the array selecting some button elements and select an option in select box, wait for iframe to load and the select box and its options to become populated before selecting the next set of buttons of the next iteration and so on. 所以基本上,我需要遍历数组,选择一些按钮元素,然后在选择框中选择一个选项,等待iframe加载,并填充选择框及其选项,然后再选择下一次迭代的下一组按钮,如此上。
It's the SetTimeout
what is making your code instantly return and therefore starting all timeouts at almost once. 是SetTimeout
使您的代码立即返回并因此几乎立即启动所有超时。
I believe you could achieve what you want by creating a recursive function instead of a for-loop: 我相信您可以通过创建递归函数而不是for循环来实现所需的功能:
var recursiveFunc = function(i) {
setTimeout(function() {
...
if(i < case.lenght - 1){
recursiveFunc(i++)
}
}, 1500 * i);
})(0)
Edit as per comments, it seems that you couldn't exhaust the stack, even if your array is too long. 根据注释进行编辑 ,即使数组太长,似乎也无法耗尽堆栈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.