What's the equivalent of Java's Thread.sleep() in JavaScript?

JavaJavascript

Java Problem Overview


What's the equivalent of Java's Thread.sleep() in JavaScript?

Java Solutions


Solution 1 - Java

The simple answer is that there is no such function.

The closest thing you have is:

var millisecondsToWait = 500;
setTimeout(function() {
    // Whatever you want to do after the wait
}, millisecondsToWait);

Note that you especially don't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.

Here are a couple of other SO questions that deal with threads in JavaScript:

And this question may also be helpful:

Solution 2 - Java

Try with this code. I hope it's useful for you.

function sleep(seconds) 
{
  var e = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= e) {}
}

Solution 3 - Java

Assuming you're able to use ECMAScript 2017 you can emulate similar behaviour by using async/await and setTimeout. Here's an example sleep function:

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

You can then use the sleep function in any other async function like this:

async function testSleep() {
    console.log("Waiting for 1 second...");
    await sleep(1000);
    console.log("Waiting done."); // Called 1 second after the first console.log
}

This is nice because it avoids needing a callback. The down side is that it can only be used in async functions. Behind the scenes the testSleep function is paused, and after the sleep completes it is resumed.

From MDN:

> The await expression causes async function execution to pause until a > Promise is fulfilled or rejected, and to resume execution of the async > function after fulfillment.

For a full explanation see:

Solution 4 - Java

There's no direct equivalent, as it'd pause a webpage. However there is a setTimeout(), e.g.:

function doSomething() {
  thing = thing + 1;
  setTimeout(doSomething, 500);
}

Closure example (thanks Daniel):

function doSomething(val) {
  thing = thing + 1;
  setTimeout(function() { doSomething(val) }, 500);
}

The second argument is milliseconds before firing, you can use this for time events or waiting before performing an operation.

Edit: Updated based on comments for a cleaner result.

Solution 5 - Java

For Best solution, Use async/await statement for ecma script 2017

await can use only inside of async function

function sleep(time) {
    return new Promise((resolve) => {
        setTimeout(resolve, time || 1000);
    });
}

await sleep(10000); //this method wait for 10 sec.

Note : async / await not actualy stoped thread like Thread.sleep but simulate it

Solution 6 - Java

You can either write a spin loop (a loop that just loops for a long period of time performing some sort of computation to delay the function) or use:

setTimeout("Func1()", 3000);

This will call 'Func1()' after 3 seconds.

Edit:

Credit goes to the commenters, but you can pass anonymous functions to setTimeout.

setTimeout(function() {
   //Do some stuff here
}, 3000);

This is much more efficient and does not invoke javascript's eval function.

Solution 7 - Java

setTimeout would not hold and resume on your own thread however Thread.sleep does. There is no actual equal in Javascript

Solution 8 - Java

Or maybe you can use the setInterval function, to call a particular function, after the specified number of milliseconds. Just do a google for the setInterval prototype.I don't quite recollect it.

Solution 9 - Java

This eventually helped me:

    var x = 0;
    var buttonText = 'LOADING';

    $('#startbutton').click(function(){
        $(this).text(buttonText);
        window.setTimeout(addDotToButton,2000);
    })

    function addDotToButton(){
        x++;
        buttonText += '.';
        $('#startbutton').text(buttonText);
    
        if (x < 4) window.setTimeout(addDotToButton, 2000);
        else location.reload(true);
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNigerView Question on Stackoverflow
Solution 1 - JavaDaniel PrydenView Answer on Stackoverflow
Solution 2 - JavaDavid MiróView Answer on Stackoverflow
Solution 3 - JavaRichrdView Answer on Stackoverflow
Solution 4 - JavaNick CraverView Answer on Stackoverflow
Solution 5 - JavaToprakView Answer on Stackoverflow
Solution 6 - JavaMalaxeurView Answer on Stackoverflow
Solution 7 - JavaErangaView Answer on Stackoverflow
Solution 8 - JavaThe MachineView Answer on Stackoverflow
Solution 9 - Javacrazymike79View Answer on Stackoverflow