I’m trying to delay a check using JavaScript. Specifically, I want the function below to wait 5 seconds before evaluating whether newState
is -1. However, it doesn’t work as expected — the condition gets checked immediately instead of after the delay.
function stateChange(newState) {
setTimeout('', 5000);
if (newState == -1) {
alert('VIDEO HAS STOPPED');
}
}
What is the right way to make JavaScript wait 5 seconds before running the if
condition?
“Start with the classic: setTimeout”
Back when I first started with JS, setTimeout
was our go-to for creating delays. Here’s how you’d do a javascript wait 5 seconds before triggering something:
function stateChange(newState) {
setTimeout(() => {
if (newState == -1) {
alert('VIDEO HAS STOPPED');
}
}, 5000);
}
What’s happening here:
You’re scheduling the alert to run after 5 seconds, without blocking the rest of your code. It’s simple and effective—but not the most elegant in complex workflows.
“Modernize it with async/await”
Right, @emma-crepeau’s version works great for straightforward stuff. But if you’re working in an async context (APIs, user flows, etc.), here’s a cleaner way to do a javascript wait 5 seconds:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function stateChange(newState) {
await delay(5000); // Wait 5 seconds
if (newState == -1) {
alert('VIDEO HAS STOPPED');
}
}
Bonus:
That delay()
function is reusable, readable, and perfect for any scenario where you need a pause. Much easier to reason about in larger async codebases.
“Quick and dirty? Inline Promise does the job”
Yep— @kumari_babitaa version is clean and reusable. But if you’re just experimenting or writing something short and sweet, here’s a no-frills way to make javascript wait 5 seconds:
async function stateChange(newState) {
await new Promise(resolve => setTimeout(resolve, 5000));
if (newState == -1) {
alert('VIDEO HAS STOPPED');
}
}
Just remember to call stateChange()
from an async function or top-level async context. No need to define a separate delay()
function if you’re just doing a one-off delay.