Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait 5 seconds before executing next line

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');   } } 
like image 817
copyflake Avatar asked Jan 09 '13 01:01

copyflake


People also ask

How do you make a function wait for a second?

To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.


1 Answers

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.

like image 65
Joseph Silber Avatar answered Sep 17 '22 17:09

Joseph Silber