更新时间:2022-10-29 23:27:44
如果你想进去你可以将url放在一个数组中并循环遍历它们,每次为下一个调用 setTimeout()
:
let urls = [https://www.bbc.com,https://www.cnn.com ,https://www.npr.org]函数openURLs(urls,i = 0){setTimeout(function(){console.log(urls [i])//或者你想在这里调用openURLs(urls) ,(i + 1)%urls.length)},1000)} openURLs(网址)
附加说明:
alert(1%3); // 1
警报(2%3); // 2
警报(3%3); // 0
alert(4%3); // 1
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.
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:
alert(1 % 3); // 1
alert(2 % 3); // 2
alert(3 % 3); // 0
alert(4 % 3); // 1