Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript sleep function by Promise in loop

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~

like image 648
Wang Avatar asked Aug 18 '26 00:08

Wang


1 Answers

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.

like image 111
Mihai Alexandru-Ionut Avatar answered Aug 20 '26 14:08

Mihai Alexandru-Ionut