如何在JavaScript中每5分钟调用一个循环中的两个交替函数?

时间:2018-05-14 21:14:54

标签: javascript loops asynchronous timeout

承认setTimeout()方法为asynchronous,因此从此开始:

for (var i = 1; i <= 3; i++) {
  (function(i) {
    setTimeout(function() {
      console.log(i + " second(s) elapsed");
    }, i * 1000);
  })(i);
}

我想替换 console.log()以及

的效果
  • window.open("https://www.twitter.com","_self") document.getElementById("myFirstID").click();

  • window.open("https://www.facebook.com","_self") document.getElementById("mySecondID").click();

交替呼叫,每个延迟,比方说,5分钟,但需要一些帮助,而不是打破它:-)所以我问。

这是一个早期(但unsuccessful)尝试:

i=0;
while(i < 100)
{
    setTimeout(function(){ window.open("https://www.bbc.com","_self") }, 3000);
    setTimeout(function(){ window.open("https://www.cnn.com","_self") }, 3000);
  i++
}

tldr;

还考虑使用switch() statement

另见:

How to make setTimeout in while loop execute sequentially in JavaScript?

JavaScript closure inside loops – simple practical example

Calling two methods alternately after every 5 minutes.

3 个答案:

答案 0 :(得分:1)

您可以使用两个函数以超时方式相互调用,就像这样。您还可以跟踪计时器,以防您在事件发生时或在一定时间后停止计时。

&#13;
&#13;
function toggleCalls () {
  var timer = {timeout: null};
  function callA () {
    console.log("A Called");
    timer.timeout = setTimeout(callB, 1000);
  }
  function callB () {
    console.log("B Called");
    timer.timeout = setTimeout(callA, 1000);
  }
  callA();
  return timer;
}

var timer = toggleCalls();

setTimeout(function () {
  clearTimeout(timer.timeout);
  console.log("stopped");
}, 5000);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果你想进入循环,你可以将网址放在一个数组中并循环遍历它们,每次都为下一个调用setTimeout()

let urls = [
    "https://www.bbc.com",
    "https://www.cnn.com",
    "https://www.npr.org"
]
function openURLs(urls, i=0){
    setTimeout(function(){
         console.log(urls[i]) // or whatever you want to call here
         openURLs(urls, (i+1) % urls.length)
        }, 1000)
}
openURLs(urls)

补充说明:

Remainder % (aka "modulo")

alert(1 % 3); // 1
alert(2 % 3); // 2
alert(3 % 3); // 0

alert(4 % 3); // 1

答案 2 :(得分:0)

尝试使用间隔功能。

  setInterval (()=> {
     // TODO inserte code here
    }, 300*1000);