How to call two alternating functions in a loop ev

2020-08-05 10:44发布

问题:

Acknowledging that the setTimeout() method is asynchronous and therefore starting with this:

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

I'd like to replace console.log() with something to the effect of

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

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

called alternatingly, each with a delay of, say, 5 minutes, but need some help replacing it without breaking it :-) Therefore I ask.


This was one early (but unsuccessful) attempt:

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;

also thought of using a switch() statement


See also:

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.

回答1:

You can have two functions that call each other with a timeout, like so. You can also keep track of the timer, in case you want to stop it when an event occurs, or after a certain duration.

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



回答2:

If you want to go in a loop you can put the urls in an array and loop over them, calling setTimeout() for the next one each time:

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)


Further notes:

Remainder % (aka "modulo")

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

alert(4 % 3); // 1


回答3:

Try to use Interval function.

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