I intend to open a series of urls in firefox,each one should be opened after another in 10 minutes, here is my code should be execute in firebug console:
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
var urls = ["https://www.google.com/","https://www.bing.com/","https://www.reddit.com/"];
for(var i = 0; i < urls.length; i++)
sleep(600000 * i).then(() => {
window.open(urls[i]);
})
But it didn't work, could anyone help me ? Thank you~
Sleep function is executing asynchronously and the for loop finished before executing any of the sleep calls.
So, the last value of for loop will be 3, and window.open function will receive as parameter the value of urls[3] which is undefined.
Have a look:
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
var urls = ["https://www.google.com/","https://www.bing.com/","https://www.reddit.com/"];
for(var i = 0; i < urls.length; i++)
sleep(600*i).then(() => {
console.log(i);
})
One solution is to use let keyword.
You should use let keyword in order to use enclosed value of i variable.
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
var urls = ["https://www.google.com/","https://www.bing.com/","https://www.reddit.com/"];
for(let i = 0; i < urls.length; i++)
sleep(6000*i).then(() => {
window.open(urls[i]);
})
jsFiddle solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With