In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "how to achieve sleep in js", the content is easy to understand, clear, hope to help you solve doubts, the following let the editor lead you to study and learn "how to achieve sleep in js" this article.
1. Use loops to achieve similar sleep
Functionsleep (d) {
For (vart=Date.now (); Date.now ()-t
SetTimeout (resolve,ms)
)
}
Sleep (3000) .then (() = > {
/ / code
})
Advantages: this approach actually uses setTimeout, does not cause process blocking, and does not cause performance and load problems.
Disadvantages: although not as many layers as callback, it is still not very beautiful, and when we need to stop execution in a process (or return the wrong value halfway), we have to jump out after layers of judgment, which is very troublesome, and this asynchronism is not so thorough, it still looks awkward.
3. Implement similar sleep through generate.
Function*sleep (ms) {
YieldnewPromise (function (resolve,reject) {
Console.log (111)
SetTimeout (resolve,ms)
})
}
Sleep (500). Next (). Value.then () = > {
Console.log (11111)
})
Pros: with the same advantages as Promise, the code becomes very simple and clean, not as stiff and disgusting as then.
Disadvantages: but the deficiency is also obvious, that is, it is troublesome to execute next () every time. Although there is a co (third-party package) to solve it, it does not look good with an extra layer of package, and the error must be handled according to the logic of co.
These are all the contents of the article "how to achieve sleep in js". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.