Reputation: 23
I am trying to make the script pause for about 1 second, then continue executing the script, but I can't seem to figure out how. Here is my code:
function hello() {
alert("Hi!")
//I need about a 1 seconed pause here;
alert("Hi again!");
}
<button onclick="hello()">Say Hi!</button>
I already tried the following:
function hello() {
alert("Hi!")
setTimeout(myFunction, 3000)//I thought this would wait, run the function, then return to the function hello()...
alert("Hi again!")
}
function myFunction {
a = document.getElementById("blank")
a.innerHTML = "wait complete"
}
<button onclick="hello()">Say Hi!</button>
<div id="blank">
...
</div>
Upvotes: 1
Views: 93
Reputation: 92440
An idiom that's becoming common as async/await is available in browsers it to make an async function and await a pause()
function the returns a promise:
let pause = (time) => new Promise(resolve => setTimeout(resolve, time))
async function hello() {
console.log("Hi!")
await pause(2000)
console.log("Hi again!");
}
<button onclick="hello()">Say Hi!</button>
Upvotes: 1
Reputation: 2578
You were on the right track with the setTimeout function:
function hello() {
alert("Hi!")
setTimeout(function() {
alert("Hi again!");
}, 1000)
}
<button onclick="hello()">Say Hi!</button>
Upvotes: 2