JavaScript实现异步sleep函数
const sleep = (timeout) => {
return new Promise((resolve)=>{
setTimeout(()=>{
resolve();
}, timeout)
})
}
const setSecretImg = async()=>{
await sleep(3000);
console.log("start")
$("#parsed_secret_img").css("background-image", "url("+g_secret_img_url+")");
$("#download_parsed_secret_img").attr('src', g_secret_img_url)
console.log("end");
}
console.log("location 1")
setSecretImg()
console.log("location 2")
执行过程说明:
- 在console中输出:location 1
- 执行setSecretImg函数,并开始计时3s;
- 在console中输出:location 2
- 3s后在控制console中输出: