Several simple ways to implement the sleep sleep function in JavaScript

Table of contents

1. What is the sleep function?

2. Why use sleep?

3. Realize sleep


1. What is the sleep function?

sleep is a function, its function is to make the program pause for a specified time, which has the effect of delaying time.

Official introduction: sleep is a function, the function is to delay, the program pauses for a certain period of time, and an interrupt exception is thrown during execution, which must be captured and processed before this function can be used.

For example:

console.log('1');
sleep(2000);
console.log('2');

After the console outputs the number 1, it will output the number 2 after an interval of 2 seconds

Of course, the above code cannot be executed, because there is no sleep method in js.

So this article mainly introduces several ways to implement sleep in js.

2. Why use sleep?

Seeing this, some people will ask, why use sleep, I can use setTimeout to achieve the above example?

Because setTimeout implements timing tasks through callback functions, callback nesting will appear in multi-tasking scenarios:

console.time('runTime:');
  setTimeout(() => {
    console.log('1');
    setTimeout(() => {
      console.log('2')
      setTimeout(() => {
        console.log('3')
        console.timeEnd('runTime:');
      }, 2000);
    }, 3000);
  }, 2000);
//结果:
//1
//2
//3
//runTime:: 7017.87890625 ms

The above method has the problem of callback nesting. We hope that the above example can be implemented more conveniently and elegantly by using the sleep function.

3. Realize sleep

Next, we will use several different methods to implement the sleep method:

  1. Implementation based on Date

    Prevent code execution through an infinite loop, and keep checking whether it times out.

    function sleep(time){
     var timeStamp = new Date().getTime();
     var endTime = timeStamp + time;
     while(true){
     if (new Date().getTime() > endTime){
      return;
     } 
     }
    }
    console.time('runTime:');
    sleep(2000);
    console.log('1');
    sleep(3000);
    console.log('2');
    sleep(2000);
    console.log('3');
    console.timeEnd('runTime:');
    // 1
    // 2
    // 3
    // runTime:: 7004.301ms

    shortcoming:

    The above code will not let the thread sleep, but make the cpu have no time to handle other tasks through high-load calculations.

    The disadvantage of this is that all other tasks will be suspended during the sleep process, including dom rendering.

    Therefore, the program will be in a state of suspended animation during the sleep process, and will not perform other tasks

  2. Promise-based sleep

    Pure Promise just changes the previous vertical nesting to horizontal nesting:

    function sleep(time){
     return new Promise(function(resolve){
     setTimeout(resolve, time);
     });
    }
    console.time('runTime:');
    console.log('1');
    sleep(1000).then(function(){
     console.log('2');
     sleep(2000).then(function(){
     console.log('3');
     console.timeEnd('runTime:');
     });
    });
    console.log('a');
    // 1
    // a
    // 2
    // 3
    // runTime:: 3013.476ms

    This is actually no different from the previous setTimeout nesting, and it is also ugly.

    Let's optimize again, using ES6's Generator function to rewrite the above example

  3. Sleep based on Generator function

    We use the Generator function to execute the sleep, and use co to perform self-execution.

    var co = require('co');
     
    function sleep(time){
     return new Promise(function(resolve){
     setTimeout(resolve, time);
     });
    }
     
    var run = function* (){
     console.time('runTime:');
     console.log('1');
     yield sleep(2000);
     console.log('2');
     yield sleep(1000);
     console.log('3'); 
     console.timeEnd('runTime:');
    }
     
    co(run);
    console.log('a');
    // 1
    // a
    // 2
    // 3
    // runTime:: 3004.935ms

    It can be seen that the overall code does not seem to have a nested relationship, and there will be no suspended animation during execution, and it will not block the execution of other tasks.

    But there is an extra reference to the co-executor, so there are still flaws.

  4. sleep based on async function

    The biggest feature of the async function is its own executor, so we can implement sleep without co

    function sleep(time){
     return new Promise((resolve) => setTimeout(resolve, time));
    }
     
    async function run(){
     console.time('runTime:');
     console.log('1');
     await sleep(2000);
     console.log('2');
     await sleep(1000);
     console.log('3'); 
     console.timeEnd('runTime:');
    }
     
    run();
    console.log('a');
     
    // 1
    // a
    // 2
    // 3
    // runTime:: 3009.984ms

Guess you like

Origin blog.csdn.net/lwx33912138/article/details/127666083