Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement delayed execution by JavaScript

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

这篇文章将为大家详细讲解有关JavaScript如何实现延时执行,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

延时执行// 比如 sleep(1000) 意味着等待1000毫秒,还可从 Promise、Generator、Async/Await 等角度实现。

// Promise

const sleep = time => {

return new Promise(resolve => setTimeout(resolve, time));

};

sleep(1000).then(() => {

console.log(1);

});// Generator

function* sleepGenerator(time) {

yield new Promise(function(resolve, reject) {

setTimeout(resolve, time);

});

}

sleepGenerator(1000)

.next()

.value.then(() => {

console.log(1);

});

//async

function sleep(time) {

return new Promise(resolve => setTimeout(resolve, time));

}

async function output() {

let out = await sleep(1000);

console.log(1);

return out;

}

output();

function sleep(callback, time) {

if (typeof callback === "function") {

setTimeout(callback, time);

}

}

function output() {

console.log(1);

}

sleep(output, 1000);关于"JavaScript如何实现延时执行"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report