What is the JavaScript version of sleep()?

Created by Dan DascalescuLinked to 16.5m issues across 142 teams


The JavaScript version of sleep() is setTimeout(). setTimeout() is a function that executes a given function after a specified number of milliseconds. For example, the following code will execute the sayHello() function after 1000 milliseconds (1 second):

setTimeout(sayHello, 1000); function sayHello() { console.log('Hello!'); }

This can be extended as a utility with a Promise:

function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }