暂停for循环的迭代?

时间:2017-07-25 05:21:35

标签: javascript loops

我希望在for循环的迭代之间添加1000毫秒的暂停。我在这里看到的所有解决方案,其中有很多,只需将循环抛入一个函数,然后从等待的setTimeout调用,然后以速度执行循环。我需要它来暂停内部循环。这是一个小提琴。

FIDDLE

var button = document.getElementsByTagName('span');
var searchText = 'Activate';
var resultDiv = document.getElementById('results');

for (var i = 0; i < button.length; i++) {
  if (button[i].textContent == searchText) {
    button[i].click();
    var div = document.createElement('div');
    div.innerHTML = 'Clicked';
    div.className = 'click';
    resultDiv.append(div);
    // pause before iterating
  }
}

2 个答案:

答案 0 :(得分:1)

这可能会对你有帮助。

var button = document.getElementsByTagName("span");
var searchText = "Activate";
var resultDiv = document.getElementById('results');

for (var i = 0; i < button.length; i++) {
  (function(j) {
    setTimeout(function() {
      if (button[j].textContent == searchText) {
        button[j].click();
        var div = document.createElement("div");
        div.innerHTML = 'Clicked';
        div.className = 'click';
        resultDiv.append(div);
      }
    }, j * 1000);
  })(i);
};
.wrapper {
  visibility: hidden;
}

.click {
  padding: 5px
}
<div class="wrapper">
  <span>Activate</span>
  <span></span>
  <span></span>
  <span>Activate</span>
  <span></span>
  <span></span>
  <span>Activate</span>
  <span>Activate</span>
  <span></span>
  <span>Activate</span>
  <span></span>
  <span></span>
  <span></span>
  <span>Activate</span>
  <span></span>
  <span></span>
  <span>Activate</span>
  <span></span>
  <span>Activate</span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span>Activate</span>
  <span></span>
  <span></span>
</div>
<div id="results">
</div>

答案 1 :(得分:1)

您可以使用setInterval(),如:

 setInterval(function () {
            if (button[i].textContent == searchText) {
    button[i].click();
    var div = document.createElement("div");
    div.innerHTML = 'Clicked';
    div.className = 'click';
    resultDiv.append(div);
    // pause before iterating
  }
  if(i==button.length){
    clearInterval()
  }
  i++;
}, 2000);