Wait 5 seconds before executing next line

JavascriptDom Events

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Browser

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.

Node.js

Node.js 16 provides a built-in version of setTimeout that is promise-based so we don't have to create our own utility function:

import { setTimeout } from "timers/promises";

const yourFunction = async () => {
  await setTimeout(5000);
  console.log("Waited 5s");

  await setTimeout(5000);
  console.log("Waited an additional 5s");
};

Solution 3 - Javascript

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 milliseconds
console.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.

Solution 4 - Javascript

If you're in an async function you can simply do it in one line:

console.log(1);
await new Promise(resolve => setTimeout(resolve, 3000)); // 3 sec
console.log(2);

FYI, if target is NodeJS you can use this if you want (it's a predefined promisified setTimeout function):

await setTimeout[Object.getOwnPropertySymbols(setTimeout)[0]](3000) // 3 sec

Solution 5 - Javascript

Use a delay function like this:

var delay = ( function() {
	var timer = 0;
	return function(callback, ms) {
		clearTimeout (timer);
		timer = setTimeout(callback, ms);
	};
})();

Usage:

delay(function(){
	// do stuff
}, 5000 ); // end delay

Credits: https://stackoverflow.com/q/1909441/1066234

Solution 6 - Javascript

You should not just try to pause 5 seconds in javascript. It doesn't work that way. You can schedule a function of code to run 5 seconds from now, but you have to put the code that you want to run later into a function and the rest of your code after that function will continue to run immediately.

For example:

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

But, if you have code like this:

stateChange(-1);
console.log("Hello");

The console.log() statement will run immediately. It will not wait until after the timeout fires in the stateChange() function. You cannot just pause javascript execution for a predetermined amount of time.

Instead, any code that you want to run delays must be inside the setTimeout() callback function (or called from that function).

If you did try to "pause" by looping, then you'd essentially "hang" the Javascript interpreter for a period of time. Because Javascript runs your code in only a single thread, when you're looping nothing else can run (no other event handlers can get called). So, looping waiting for some variable to change will never work because no other code can run to change that variable.

Solution 7 - Javascript

This solution comes from React Native's documentation for a refresh control:

function wait(timeout) {
    return new Promise(resolve => {
        setTimeout(resolve, timeout);
    });
}

To apply this to the OP's question, you could use this function in coordination with await:

await wait(5000);
if (newState == -1) {
    alert('Done');
}

Solution 8 - Javascript

Try this:

//the code will execute in 1 3 5 7 9 seconds later
function exec() {
    for(var i=0;i<5;i++) {
        setTimeout(function() {
            console.log(new Date());   //It's you code
        },(i+i+1)*1000);
    }
}

Solution 9 - Javascript

setTimeout(function() {
     $('.message').hide();
}, 5000);

This will hide the '.message' div after 5 seconds.

Solution 10 - Javascript

Best way to create a function like this for wait in milli seconds, this function will wait for milliseconds provided in the argument:

function waitSeconds(iMilliSeconds) {
    var counter= 0
        , start = new Date().getTime()
        , end = 0;
    while (counter < iMilliSeconds) {
        end = new Date().getTime();
        counter = end - start;
    }
}

Solution 11 - Javascript

Based on Joseph Silber's answer, I would do it like that, a bit more generic.

You would have your function (let's create one based on the question):

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

And you could have a wait function:

function wait(milliseconds, foo, arg){
    setTimeout(function () {
        foo(arg); // will be executed after the specified time
    }, milliseconds);
}

At the end you would have:

wait(5000, videoStopped, newState);

That's a solution, I would rather not use arguments in the wait function (to have only foo(); instead of foo(arg);) but that's for the example.

Solution 12 - Javascript

You can add delay by making small changes to your function ( async and await ).

const addNSecondsDelay = (n) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve();
    }, n * 1000);
  });
}

const asyncFunctionCall = async () {

  console.log("stpe-1"); 
  await addNSecondsDelay(5);
  console.log("step-2 after 5 seconds delay"); 

}

asyncFunctionCall();

Solution 13 - Javascript

using angularjs:

$timeout(function(){
if(yourvariable===-1){
doSomeThingAfter5Seconds();
}
},5000)

Solution 14 - Javascript

Create new Js function

function sleep(delay) {
        var start = new Date().getTime();
        while (new Date().getTime() < start + delay);
      }

Call the function when you want to delay execution. Use milliseconds in int for delay value.

####Some code
 sleep(1000);
####Next line

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncopyflakeView Question on Stackoverflow
Solution 1 - JavascriptJoseph SilberView Answer on Stackoverflow
Solution 2 - JavascriptEtienne MartinView Answer on Stackoverflow
Solution 3 - JavascriptMicView Answer on Stackoverflow
Solution 4 - JavascriptShlView Answer on Stackoverflow
Solution 5 - JavascriptAvatarView Answer on Stackoverflow
Solution 6 - Javascriptjfriend00View Answer on Stackoverflow
Solution 7 - Javascriptbearacuda13View Answer on Stackoverflow
Solution 8 - JavascriptSteve JiangView Answer on Stackoverflow
Solution 9 - JavascripthackernewbieView Answer on Stackoverflow
Solution 10 - JavascriptJitendra Pal - JPView Answer on Stackoverflow
Solution 11 - JavascriptSylhareView Answer on Stackoverflow
Solution 12 - Javascriptp.durga shankarView Answer on Stackoverflow
Solution 13 - JavascriptDr. AbbosView Answer on Stackoverflow
Solution 14 - JavascriptMadushanka SampathView Answer on Stackoverflow