循环中的Promise javascript睡眠功能

时间:2017-08-11 06:50:42

标签: javascript loops sleep

我打算在firefox中打开一系列网址,每一个应该在10分钟后陆续打开,这里是我的代码应该在firebug控制台中执行:

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

但它没有用,任何人都可以帮助我吗?谢谢〜

5 个答案:

答案 0 :(得分:4)

在执行任何Sleep调用之前,

for函数正在执行异步并且sleep循环已完成。

因此,for循环的最后一个值为3,而window.open函数将作为参数接收未定义的value urls[3]

看看:

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

一种解决方案是使用let关键字。

您应该使用let关键字来使用i变量的附加值。

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.

答案 1 :(得分:0)

您可以使用setInterval()或setTimeout()代替睡眠来实现此目的。

答案 2 :(得分:0)

问题是在所有3个案例中我将= 3,所以你需要保存我,例如

function sleep (time, i) {
    return new Promise((resolve) => setTimeout(() => resolve(i), time));
}
var urls = ["https://www.google.com/","https://www.bing.com/","https://www.reddit.com/"];
for(var i = 0; i < urls.length; i++)
    sleep(1 * i, i).then((index) => {
    console.log(urls[index]); 
})

但即使这样也无济于事,因为第一个新标签页会打开,非活动标签中的代码会被浏览器停止。

答案 3 :(得分:0)

认为间隔+ entries更适合这个,这是es6的一个例子

const urls = [
  'https://www.google.com/',
  'https://www.bing.com/',
  'https://www.reddit.com'
]

const entries = urls.entries()

const loop = setInterval(() => {
  const {value, done} = entries.next()
  done ? clearInterval(loop) : open(value)
}, 600 * 10)

答案 4 :(得分:0)

Promise与async / await函数一起很好地工作。

以下内容将声明一个新的异步函数(即它将在​​调用该函数后在外部执行)。异步函数的代码很容易读取,因为它的读取方式类似于同步函数:

function sleep(time) {
    return new Promise((resolve) => setTimeout(resolve, time))
}

(async function() {
    const urls = ["https://www.google.com/","https://www.bing.com/","https://www.reddit.com/"]
    for (let url of urls) {
        await sleep(1000)
        console.log(url)
    }
})()