如何减慢JavaScript中的循环

时间:2019-05-19 22:29:18

标签: javascript performance loops

您好,我正在进行for循环以从iframe获取数据。但是循环太快了。我如何放慢循环速度,以在50-100毫秒或更长时间内执行每次迭代?

        for (let i = 113361978; i < 113371978; i++) {

        fetch('https://vimeo.com/api/oembed.json?url=https://player.vimeo.com/video/' + i)
        .then(res => res.json())
        .then(
            (json) => {
                console.log(i);
                if (json.author_name === 'Chuck Norris') {
                    document.write(`<iframe src="https://player.vimeo.com/video/${i}" width="640" height="640" frameborder="0" allowfullscreen=""></iframe>`);
                }   
            }
        )
    }

我也尝试使用setInterval,但是我的i变量不等于result并以错误的ID显示iframe。

                let i = 220316094;
                function loop(){

                    fetch('https://vimeo.com/api/oembed.json?url=https://player.vimeo.com/video/' + i)
                        .then(res => res.json())
                        .then(
                            (json) => {
                                console.log(i);
                                if (json.author_name === 'Chuck Norris') {
                                    document.write(`<iframe src="https://player.vimeo.com/video/${i}" width="640" height="640" frameborder="0" allowfullscreen=""></iframe>`);
                                }

                            }
                        ).then(i++) 
                }

                function loop2(){
                    setInterval(loop, 50);
                }
                loop2()

1 个答案:

答案 0 :(得分:0)

拥抱''async,以便更轻松地遵循异步代码。

现在您可以将函数重写为

await

现在定义一个异步async function doTheDownloads(){ for (let i = 113361978; i < 113371978; i++) { const url = 'https://vimeo.com/api/oembed.json?url=https://player.vimeo.com/video/' + i const res = await fetch(url) const json = await res.json() if (json.author_name === 'Chuck Norris') { document.write(something); //you probably want a different approach here } } } 函数

delay

并在循环中使用它

const delay = t => new Promise(resolve => setTimeout(resolve, t))

async function doTheDownloads(){
    for (let i = 113361978; i < 113371978; i++) {
        const url = 
          'https://vimeo.com/api/oembed.json?url=https://player.vimeo.com/video/' + i
        const res = await fetch(url)
        const json = await res.json()
        if (json.author_name === 'Chuck Norris') {
            document.write(something); //you probably want a different approach here
        } 
        await delay(1000) //wait for 1s
    }
}