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中输出:
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!