javascript – Wait 5 seconds before executing next line
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.
Heres 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.
javascript – Wait 5 seconds before executing next line
You really shouldnt be doing this, the correct use of timeout is the right tool for the OPs 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);
Ive 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, its creating a Date() object in a while loop, which might very overwhelm the GC if it runs long enough. But I cant emphasize enough, this is only suitable for testing, for building any actual functionality you should refer to Joseph Silbers answer.
Related posts on java script :
- How do you use Math random and Math floor in JavaScript?
- How can I extract a number from a string in JavaScript?
- How do you get the current URL with JavaScript?
- Does JavaScript support optional chaining?
- What does parseFloat mean in JavaScript?
- Is JavaScript by reference or by value?
- How do I put JavaScript in HTML?
- Should I disable JavaScript on Safari?
- Are Java and JavaScript are same?