X
Home
Topics
Control Panels
Hosting
Linux & Serverless
WordPress
PHP
Javascript
React & React Native
CSS (& HTML)
Node.js
SQL & No SQL
Miscellaneous
About
Contact
Resources
Archive

Javascript Equivalent of Sleep Function in PHP, How to Pause Execution in Javascript

This will do the trick, I won’t go into how to create “promises from scratch”, but that is how you can do it in Javascript. In fact there is NO pre-made, set function designed to do just what the PHP sleep() function does. Don’t ask me why, but there isn’t.

In the script below you pass 3000 to our function called “sleep”, which represents 3000 milliseconds. We call it with “action” at the end.

const sleep = (ms) => {

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


const action = async ()=> {
    for(let i = 1; i < 5; i++){
        console.log('start: ' + i);
        await sleep(3000);
        console.log("finished: " + i);
    }


}

action()

Please visit my Web Developer Site for more information.