Several ways to implement the sleep function in js

The role of the sleep function is to let the thread sleep and wait until the specified time to wake up again.

Method 1: This implementation uses a pseudo-infinite loop to block the main thread. Because JS is single threaded. So in this way, the real sleep() can be realized.

 function sleep(delay) { var start = (new Date()).getTime(); while ((new Date()).getTime() - start < delay) { continue; } } function test() { console.log('111'); sleep(2000); console.log('222'); } test()

Method 2: Timer

 function sleep1(ms, callback) { setTimeout(callback, ms) } //sleep 1s

The post js several ways to implement the sleep function first appeared on Lenix Blog .

This article is reprinted from https://blog.p2hp.com/archives/8913
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment