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 explanation of the difference between Vue life cycle

Life cycle classification Each component of vue i...

MySQL 5.7 installation and configuration tutorial under CentOS7 64 bit

Installation environment: CentOS7 64-bit MINI ver...

Detailed explanation of Vue lazyload picture lazy loading example

Documentation: https://github.com/hilongjw/vue-la...

Detailed explanation of Vue's SSR server-side rendering example

Why use Server-Side Rendering (SSR) Better SEO, s...

MySQL master-slave configuration study notes

● I was planning to buy some cloud data to provid...

JavaScript implements long image scrolling effect

This article shares the specific code of JavaScri...

How to display the border when td is empty

Previously, I summarized how to use CSS to achieve...

How to check and organize website files using Dreamweaver8

What is the purpose of creating your own website u...

Vue scroll down to load more data scroll case detailed explanation

vue-infinite-scroll Install npm install vue-infin...

Database query optimization: subquery optimization

1. Case Take all employees who are not the head o...

MySql 5.6.36 64-bit green version installation graphic tutorial

There are many articles about MySQL installation ...

How to enable JMX monitoring through Tomcat

Build a simulation environment: Operating system:...