javascript - 如何减慢javascript中的循环
问题描述
您好,我正在制作一个 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 变量不等于结果并显示带有错误 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()
解决方案
拥抱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
}
}
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()
const el = document.body.innerHTML += json.html
await delay(1000) //wait for 1s
break; // <= remove this
}
}
doTheDownloads()
推荐阅读
- traefik - Traefik 2 全局设置 passHostHeader 而不是每个服务?
- dhis-2 - DHIS2 API 获取数据集而不是单个数据元素
- java - 无法在android中启动Activity
- postgresql - 无密码用户的 PostgreSQL 本地数据库访问
- cucumber-jvm - Cucumber 版本 - 6.9.1 - 无法在场景大纲“示例”中传递空白字符串
- jsonschema - 是否可以创建有时可以为空而有时不能的模式引用?
- c - 使用宏的函数参数
- vba - 从 SAP 到 Excel 的小数分隔符问题:“1,056”与“1.056”(因子 1000)
- node.js - 节点快递)我遇到了这个问题
- apache-spark - 来自多列的 Pyspark 日期格式