Use of JavaScript sleep function

Use of JavaScript sleep function

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 3s

const 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:
  • JavaScript functional programming basics
  • An article teaches you JS function inheritance
  • JavaScript Basics Series: Functions and Methods
  • JS function call, apply and bind super detailed method
  • JavaScript function call, apply and bind method case study
  • Detailed explanation of the difference between arrow functions and normal functions in JavaScript
  • JavaScript knowledge: Constructors are also functions
  • Detailed examples of variable and function promotion in JavaScript
  • Summary of 50+ Utility Functions in JavaScript
  • 15 JavaScript functions worth collecting

<<:  How MLSQL Stack makes stream debugging easier

>>:  How to use Linux to calculate the disk space occupied by timed files

Recommend

Detailed process of using vmware to test PXE batch installation server

Table of contents 1. Preparation 1. Prepare the e...

Let's talk about bitwise operations in React source code in detail

Table of contents Preface Several common bit oper...

Solution to the long delay of MySQL database master-slave replication

Preface The delay of MySQL master-slave replicati...

The meaning of the 5 types of spaces in HTML

HTML provides five space entities with different ...

Some experience in building the React Native project framework

React Native is a cross-platform mobile applicati...

A brief discussion on how to learn JS step by step

Table of contents Overview 1. Clearly understand ...

Practice of el-cascader cascade selector in elementui

Table of contents 1. Effect 2. Main code 1. Effec...

Example of how to implement underline effects using Css and JS

This article mainly describes two kinds of underl...

How to match the size of text in web design: small text, big experience

With the rise of mobile terminals such as iPad, p...

MySQL data compression performance comparison details

Table of contents 1. Test environment 1.1 Hardwar...

Element uses scripts to automatically build new components

Table of contents background How does element-ui&...