停止setTimeout循环,单击按钮后激活

时间:2018-09-15 21:47:25

标签: javascript

我想旋转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中打开最后一个网址后,如何停止此循环?

2 个答案:

答案 0 :(得分:0)

将超时分配给变量,然后在其上调用clearTimeout

var myVar;

function myFunction() {
    myVar = setTimeout(function(){ alert("Hello"); }, 3000);
}

function myStopFunction() {
    clearTimeout(myVar);
}

来自https://www.w3schools.com/jsref/met_win_cleartimeout.asp

答案 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>