延迟与settimeout和for循环 [英] delay with settimeout and for loop
问题描述
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);
}
我想通过foor循环更改此代码中的数字"1",因此我想创建一个代码,该代码单击名为"something"的元素. 我创建了以下代码,但无法正常工作:
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);
}
}
如果要以一定间隔打印每个元素,则需要将计时值与整数相乘,否则所有这些元素将同时记录. /p>
此外,您可能无需在循环内创建myFunction
for (var x = 1; x < 5; x++) {
(function(i) {
setTimeout(function() {
console.log(i);
}, i * 1000)
}(x))
}
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);
}
}
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))
}
这篇关于延迟与settimeout和for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!