[英]Stop setTimeout loop, activated after click on button
我想旋轉iframe中textarea的網址列表。 這是我的代碼如下所示:
<script>
document.getElementById("addurls").onclick = function () {
var urls = $('#allurls').val().split('\n');
var index = 0;
var el = document.getElementById("indexer");
setTimeout(function rotate() {
if (index === urls.length) {
index = 0;
}
el.src = urls[index];
index++;
setTimeout(rotate, 1000);
}, 0);
};
</script>
但是,如何在iframe中打開最后一個網址后停止此循環?
將超時分配給變量,然后在其上調用clearTimeout
。
var myVar;
function myFunction() {
myVar = setTimeout(function(){ alert("Hello"); }, 3000);
}
function myStopFunction() {
clearTimeout(myVar);
}
這正是您想要的(您可以在測試后刪除控制台stmt),
<script>
document.getElementById("addurls").onclick = function () {
var allurls = document.getElementById("allurls"); //$('#allurls').val().split('\n');
var urls = allurls.value.split('\n');
var el = document.getElementById("indexer");
var index = 0;
timer = setTimeout(function rotate() {
if (index === urls.length) {
clearTimeout(timer);
return true;
}
el.src = urls[index];
console.log("TEST: ", index);
index++;
timer = setTimeout(rotate, 2000);
}, 0);
};
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.