Wait 5 seconds before executing next line

copyflake picture copyflake · Jan 9, 2013 · Viewed 1.1M times · Source

This function below doesn’t work like I want it to; being a JS novice I can’t figure out why.

I need it to wait 5 seconds before checking whether the newState is -1.

Currently, it doesn’t wait, it just checks straight away.

function stateChange(newState) {
  setTimeout('', 5000);

  if(newState == -1) {
    alert('VIDEO HAS STOPPED');
  }
}

Answer

Joseph Silber picture Joseph Silber · Jan 9, 2013

You have to put your code in the callback function you supply to setTimeout:

function stateChange(newState) {
    setTimeout(function () {
        if (newState == -1) {
            alert('VIDEO HAS STOPPED');
        }
    }, 5000);
}

Any other code will execute immediately.