1.sleep function JavaScript runs in a single thread and does not have a built-in sleep function. Now we simulate the effect of delaying execution by using sleep. Use the sleep function to implement the traffic light code, red light for 2 seconds, yellow light for 1 second, green light for 3 seconds, and change color in a cycle. 2. setTimeout The method of directly using setTimeout to implement sleep() has the best compatibility, but the implementation method using callback functions makes the code less readable and maintainable. // setTimeout let fun = () => console.log('time out'); let sleep = function(fun,time){ setTimeout(()=>{ fun(); },time); } sleep(fun,2000); setTimeout setTimeout is the most basic implementation method. The code is as follows, using recursion to implement a cyclic color change: function changeColor(color) { console.log('traffic-light ', color); } function main() { changeColor('red'); setTimeout(()=>{ changeColor('yellow'); setTimeout(() => { changeColor('green'); setTimeout(main, 2000); }, 1000); }, 2000); } main(); 3. Promise In the ES6 syntax, Promise is a way to implement the sleep method asynchronously. With the help of the Promise method, the sleep implementation method can be elegantly constructed, avoiding the use of function callbacks. // promise let fun = () => console.log('time out'); let sleep2 = (time) => new Promise((resolve) => { setTimeout(resolve,time) }) sleep2(2000).then(fun); Promises Use Promise to write the next color change in then, and finally use recursion to complete the loop. Use promise instead of setTimeout, and use chain calls and then to realize the light conversion. Then returns a promise object. When this object is in the resolved state, then can be called continuously. const traffic_light=(color,duration)=>{ return new Promise((resolve,reject)=>{ console.log('traffic-light ', color); setTimeout(()=>{ resolve() },duration) }) } const main=()=>{ Promise.resolve() .then(()=>{ return traffic_light('red',3000) }) .then(()=>{ return traffic_light('yellow',1000) }) .then(()=>{ return traffic_light('green',2000) }) .then(()=>{ main(); }) } main() 4. async await Async await is actually the syntactic sugar of generator and promise. It provides a synchronous programming method to implement asynchronous calls, while also supporting the semantics of the sleep function. It is also a commonly used way to implement sleep. // async await async function wait(time){ await sleep2(time); fun(); } wait(3000); async await usage Using async await can avoid the series of .then.then.then of Promise, and there is no need for recursion. You can use while(true) to implement the loop. function sleep(duration) { return new Promise(resolve => { setTimeout(resolve, duration); }) } async function changeColor(color, duration) { console.log('traffic-light ', color); await sleep(duration); } async function main() { while (true) { await changeColor('red', 2000); await changeColor('yellow', 1000); await changeColor('green', 3000); } } main(); 5. Output 1 after 1s, output 2 after 2s, output 3 after 3sconst log = console.log; const sleep = (timeout) => { return new Promise((resolve)=>{ setTimeout(()=>{ resolve(); }, timeout) }) } const main = async()=>{ await sleep(1000); log(1); await sleep(2000); log(2); await sleep(3000); log(3); } Reference articles:Traffic light Traffic light This is the end of this article about the use of JavaScript sleep function. For more relevant JavaScript sleep function content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: How MLSQL Stack makes stream debugging easier
>>: How to use Linux to calculate the disk space occupied by timed files
Life cycle classification Each component of vue i...
Installation environment: CentOS7 64-bit MINI ver...
Documentation: https://github.com/hilongjw/vue-la...
Why use Server-Side Rendering (SSR) Better SEO, s...
● I was planning to buy some cloud data to provid...
This article shares the specific code of JavaScri...
Previously, I summarized how to use CSS to achieve...
What is the purpose of creating your own website u...
vue-infinite-scroll Install npm install vue-infin...
1. Case Take all employees who are not the head o...
When multiple images are introduced into a page, ...
There are many articles about MySQL installation ...
What is nGrinder? nGrinder is a platform for stre...
Preface In daily work or study, it is inevitable ...
Build a simulation environment: Operating system:...