延迟与settimeout和for循环 [英] delay with settimeout and for loop

查看:145
本文介绍了延迟与settimeout和for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这里获得以下代码: 如何在JavaScript循环中添加延迟? /a> 我在IE的控制台中使用它,在此代码之后,我在控制台中使用myFunction()调用该函数以运行它;第一个代码运行良好,它单击第二个标记为"something"的元素10次,两次单击之间的延迟为3000毫秒.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆