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'); } }
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With