What Is the JavaScript Equivalent To The PHP sleep() Function?

JavaScript does not have a direct equivalent to the PHP sleep() function, which pauses the execution of a script for a specified number of seconds. However, there are a few ways to achieve similar functionality in JavaScript.

UNLIMITED DOWNLOADS: Email, admin, landing page & website templates

Starting at only $16.50 per month!

 

Using setTimeout()

The setTimeout() function is a built-in JavaScript function that allows you to run a piece of code after a specified amount of time. You can use it to create a delay in your script. Here’s an example:

console.log('Before Sleep');
setTimeout(() => {
  console.log('After Sleep');
}, 3000);

In the example above, the console.log('Before Sleep') statement will be executed immediately, followed by a 3-second delay, after which the console.log('After Sleep') statement will be executed.

Using async/await

Another way to create a delay in JavaScript is to use the async/await syntax. With async/await, you can write asynchronous code that runs in a way that is similar to synchronous code. For example:

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

async function main() {
  console.log('Before Sleep');
  await sleep(3000);
  console.log('After Sleep');
}

main();

In this example, we’ve created an async function called sleep that returns a Promise that resolves after a specified amount of time. The main function uses the await keyword to wait for the sleep function to complete, effectively creating a 3-second delay.

Note that async/await is only supported in modern browsers and requires a runtime with support for Promises.

Both of these methods can be used to achieve a similar result to the PHP sleep() function, but with different syntax and limitations. Choose the method that works best for your use case.

Further reading.