我想旋转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中打开最后一个网址后,如何停止此循环?
答案 0 :(得分:0)
将超时分配给变量,然后在其上调用clearTimeout
。
var myVar;
function myFunction() {
myVar = setTimeout(function(){ alert("Hello"); }, 3000);
}
function myStopFunction() {
clearTimeout(myVar);
}
答案 1 :(得分:0)
这正是您想要的(您可以在测试后删除控制台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>