JavaScript doesn’t have a sleep function that will delay a program’s execution for a given number of seconds. However, you can create a delay in JavaScript is to use its setTimeout method.
A setTimeout will pause a 1-second function or code in JavaScript pause for 1 second.
1000 MS = 1 SEC
console.log("Hello");
setTimeout(() => { console.log("World!"); }, 1000);
JavaScript pause for 1 second Example code
Let’s see HTML example code to print log “Hello” to the console, then after one second “World!”
<!DOCTYPE html>
<html>
<body>
<script>
console.log("Hello");
setTimeout(() => { console.log("World!"); }, 1000);
</script>
</body>
</html>
Output:
JS Sleep Function with 1 second delay
Let’s set a time delay in the JavaScript function.
var delayInMilliseconds = 1000; //1 second
setTimeout(function() {
//your code to be executed after 1 second
}, delayInMilliseconds);
Recursively call a method
A program for recursively calling a method that performs the check every second using setTimeout:
var check = function(){
if(condition){
// run when condition is met
}
else {
setTimeout(check, 1000); // check again in a second
}
}
check();
Do comment if you have any doubts and suggestions on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version