如何在JavaScript中每5分钟调用一个循环中的两个交替函数? [英] How to call two alternating functions in a loop every 5 minutes in JavaScript?
问题描述
承认 setTimeout()
方法是异步,因此从这开始:
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分钟,但需要一些帮助,而不是打破它:-)因此我问。
这是一个早期(但不成功)尝试:
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()
声明
参见:
如何在while循环中使setTimeout在JavaScript中按顺序执行?
如果你想进去你可以将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")
ordocument.getElementById("myFirstID").click();
and
window.open("https://www.facebook.com","_self")
ordocument.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
这篇关于如何在JavaScript中每5分钟调用一个循环中的两个交替函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!