js 实现sleep函数
1.sleep函数
sleep函数作用是让线程休眠,等到指定时间在重新唤起。
2、sleep实现
<!DOCTYPE html>
<html lang="zh">
<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>js sleep函数</title>
</head>
<body>
<script type="text/javascript">
//方法一
function sleep1(ms, callback) {
setTimeout(callback, ms)
}
//sleep 1s
sleep1(1000, () => {
console.log(1000)
})
//方法二
function sleep2(ms) {
return new Promise(function(resolve, reject) {
setTimeout(resolve, ms)
})
}
sleep2(1000).then(() => {
console.log(2000)
})
//方法三
function sleep3(ms) {
return new Promise(function(resolve, reject) {
setTimeout(resolve, ms)
})
}
async function init() {
await sleep3(1000);
}
init().then(() => {
console.log(3000)
})
</script>
</body>
</html>
作者:孟繁贵 Email:meng010387@126.com 期待共同进步!