Show Output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript Sleep Between Execution</title> <script> async function doStuff(){ // Code to run before sleep var hintDiv = document.getElementById("hint"); hintDiv.insertAdjacentHTML('afterbegin', '<p>An alert will be shown in 3 seconds.</p>'); // Sleep for 3 seconds await new Promise(r => setTimeout(r, 3000)); // Code to run after sleep alert("This is really slow!"); hintDiv.insertAdjacentHTML('beforeend', '<p>You have seen the alert. Goodbye!</p>'); } </script> </head> <body> <div id="hint"></div> <button type="button" onclick="doStuff()">Run Script</button> </body> </html>