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...
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.
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.
The JavaScript version of sleep() is “await”. The await feature pauses the current aync function.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With