Wait 5 seconds before executing next line Wait 5 seconds before executing next line javascript javascript

Wait 5 seconds before executing next line


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.


Here's a solution using the new async/await syntax.

Be sure to check browser support as this is a language feature introduced with ECMAScript 6.

Utility function:

const delay = ms => new Promise(res => setTimeout(res, ms));

Usage:

const yourFunction = async () => {  await delay(5000);  console.log("Waited 5s");  await delay(5000);  console.log("Waited an additional 5s");};

The advantage of this approach is that it makes your code look and behave like synchronous code.


You really shouldn't be doing this, the correct use of timeout is the right tool for the OP's problem and any other occasion where you just want to run something after a period of time. Joseph Silber has demonstrated that well in his answer. However, if in some non-production case you really want to hang the main thread for a period of time, this will do it.

function wait(ms){   var start = new Date().getTime();   var end = start;   while(end < start + ms) {     end = new Date().getTime();  }}

With execution in the form:

console.log('before');wait(7000);  //7 seconds in millisecondsconsole.log('after');

I've arrived here because I was building a simple test case for sequencing a mix of asynchronous operations around long-running blocking operations (i.e. expensive DOM manipulation) and this is my simulated blocking operation. It suits that job fine, so I thought I post it for anyone else who arrives here with a similar use case. Even so, it's creating a Date() object in a while loop, which might very overwhelm the GC if it runs long enough. But I can't emphasize enough, this is only suitable for testing, for building any actual functionality you should refer to Joseph Silber's answer.