问题
I have this code from here: How do I add a delay in a JavaScript loop? I use it in console in IE, and after this code I call the function with myFunction() in console to run; This first code runs perfectly, it clicks on the second "something" tagnamed element 10 times and between the clicks are 3000 ms delay.
function myFunction() {
(function myLoop (i) {
setTimeout(function () {
document.getElementsByTagName("something")[1].click();
if (--i) myLoop(i); // decrement i and call myLoop again if i > 0
}, 3000)
})(10);
}
I would like to change the number "1" in this code with foor loop, so I want create a code which clicks on elements named "something". I created this code, but is not working:
for (x=1;x<10;x++){
function myFunction() {
(function myLoop (i) {
setTimeout(function () {
document.getElementsByTagName("something")[1].click();
if (--i) myLoop(i); // decrement i and call myLoop again if i > 0
}, 3000)
})(10);
}
}
回答1:
If you want to print each element at an interval you need to multiply the timing value with an integer, otherwise all of them will be logged at one time.
Also you may not need to create myFunction
inside the loop
for (var x = 1; x < 5; x++) {
(function(i) {
setTimeout(function() {
console.log(i);
}, i * 1000)
}(x))
}
回答2:
It usually easier to use setInterval
rather the a loop with setTimeout
. Everything is just simpler:
var count = 10
var intv = setInterval(function(){
if (count === 0 ) {
clearInterval(intv)
console.log("done")
return
}
// do something
console.log(count--)
}, 1000)
But you can recursively call setTimeout
:
(function myLoop (i) {
setTimeout(function () {
console.log("loop: ", i)
if (--i) myLoop(i);
}, 1000)
})(10);
Putting the whole thing in a for loop AND calling it recursively is strange though, because the loop will run and make a bunch of individual timeouts that will all run independently, which I don't think is what you want.
回答3:
function myFunction() {
(function myLoop (i) {
setTimeout(function () {
document.getElementsByTagName("div")[1].click();
if (--i) myLoop(i); // decrement i and call myLoop again if i > 0
}, 3000)
})(10);
}
for (x=1;x<10;x++){
myFunction();
}
<div>1</div>
Try like this. I used div
instead of something
来源:https://stackoverflow.com/questions/53407769/delay-with-settimeout-and-for-loop