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
Table of contents 1. Preparation 1. Prepare the e...
1. Write a split script (splitNginxLog.sh) * Beca...
Table of contents Preface Several common bit oper...
Preface The delay of MySQL master-slave replicati...
1. ROW_NUMBER() Definition: The ROW_NUMBER() func...
HTML provides five space entities with different ...
React Native is a cross-platform mobile applicati...
Table of contents Overview 1. Clearly understand ...
Table of contents 1. Effect 2. Main code 1. Effec...
Enter net start mysql in cmd and the prompt is: T...
This article mainly describes two kinds of underl...
With the rise of mobile terminals such as iPad, p...
Table of contents 1. Test environment 1.1 Hardwar...
The <TH> tag is used to set the properties ...
Table of contents background How does element-ui&...