2017-07-25 102 views
1

我想在for循環的迭代之間添加一個1000ms的暫停。我在這裏看到的所有解決方案(其中有很多)只是簡單地將循環引入一個函數,然後從等待的setTimeout中調用該函數,然後以高速執行循環。我需要它暫停裏面的循環。這是一個小提琴。暫停for循環的迭代?

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 
    } 
} 

回答

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>

+0

真棒。我試圖重構它,所以延遲只發生在點擊之後(當textContent === searchText)......但是以全速度通過其他跨度時。 –

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);