What is the correct way to make JavaScript wait 5 seconds before executing the next line of code, and how can I fix my function?

“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');
  }
}

:memo: 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.