I am writing a webpage with the following structure:
In order to guarantee correctness, the table need to be updated only after the other table is fully updated (i.e., done with computation). However, I don't know how to effectively achieve this, and I could not find any wait
facility within JavaScript.
For now, I am using the following method:
updated
and make it false
;while
loop until updated
is true
;updated
to true
.This seems unintuitive to me but I cannot think of any other way of doing it. Is there any good ways to do this?
Thanks for any inputs!
Create a Simple Delay Using setTimeout log("Hello"); setTimeout(() => { console. log("World!"); }, 5000); This would log “Hello” to the console, then make JavaScript wait 5 seconds, then log “World!” to the console. And in many cases, this is enough: do something, wait, then do something else.
If you are looking to block the execution of code with call to sleep , then no, there is no method for that in JavaScript . JavaScript does have setTimeout method. setTimeout will let you defer execution of a function for x milliseconds.
JavaScript provides a setTimeout() method which can work with the callback function and the await keyword to wait for a function to finish. The objective of employing these methods is to execute a piece of code after waiting for a specific time.
In 2022, it's useful to have an event listener that fires off a Promise (which can be used in promise-chains, or async/await code). A clean way to make one:
function getPromiseFromEvent(item, event) {
return new Promise((resolve) => {
const listener = () => {
item.removeEventListener(event, listener);
resolve();
}
item.addEventListener(event, listener);
})
}
async function waitForButtonClick() {
const div = document.querySelector("div")
const button = document.querySelector("button")
div.innerText = "Waiting for you to press the button"
await getPromiseFromEvent(button, "click")
div.innerText = "The button was pressed!"
}
waitForButtonClick()
<button>ClickMe</button>
<div></div>
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