验证中...
async和await实现函数的休眠效果.html
Raw Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
//async和await实现函数的休眠效果
function sleep(interval, i) {
return new Promise(resolve => {
setTimeout(resolve, interval, i*10);//其中resolve的内容会传给 await的结果res
});
}
// 用法
async function one2FiveInAsync() {
for(let i = 1; i <= 5; i++) {
const res = await sleep(1000, i);
console.log(i, res);//每隔一秒钟打印一次 1, 10 2,20 3,30, 4,40, 5,50
}
}
one2FiveInAsync();
</script>
</body>
</html>

Comment list( 0 )

You need to Sign in for post a comment

Help Search