How to implement sleep in js
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!