Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a sleep in javascript?

Does anyone know how can I make a sleep in javascript before next line been read by the system?

example:

    1 var chkResult = Validation();
    2 //sleep here for for 10 sec before the next line been read    
    3   
    4 document.getElementById('abc').innerHTML = chkResult;

For this example, how can I make the javascript sleep/wait in line 2 for 10 sec before it continues to read line 4? I had tried setTimeout('', 10000); but it's seems not working for me still...

like image 888
Jin Yong Avatar asked Jun 24 '09 06:06

Jin Yong


People also ask

Is there a sleep function in JavaScript?

Unlike Java or Python, Javascript does not have a built-in sleep function. So, how might you be able to implement a method with the same functionality as the sleep function? A simple way to create a delay in Javascript is to use the setTimeout method.

How do you wait 1 second in JavaScript?

To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.

What is the JavaScript version of sleep?

The JavaScript version of sleep() is “await”. The await feature pauses the current aync function.


2 Answers

I Have the Hat has given the right hint. Use the setTimeout method to execute your forth line code after 10 seconds:

var chkResult = Validation();
var timeout = window.setTimeout(function() {
    document.getElementById('abc').innerHTML = chkResult;
}, 10000);

Storing the timeout ID in a variable can be handy if you want to clear a timeout.

like image 51
Gumbo Avatar answered Oct 04 '22 06:10

Gumbo


Try

setTimeout(function() { return true; }, 10000);

The first argument expects a function. This is from memory; I haven't tested it.

Edit: What Gumbo said... late here... not sure what I was thinking.

like image 38
Rex Miller Avatar answered Oct 04 '22 07:10

Rex Miller