Reputation: 1614
I have two functions and I need a forced delay between those two consecutive function calls. That is to say,
a // call func a
delay(100) // delay for 100 ms
b // call func b
Is there anyway to do so?
Edit: tried
a();
console.log("a");
setTimeout(b(), 1000);
console.log("b");
Upvotes: 2
Views: 3458
Reputation: 281764
All you need to do is to make use of setTimeout function
to call b
after calling a
a() // call func a
setTimeout(b, 100) // delay for 100 ms
if you need to keep b
function bound to the current scope, use:
setTimeout(() => b(), 100) // () => {} functions are always bound to the current scope
Upvotes: 4
Reputation: 663
Try this:
a() // First call function a
Then call function b in setTimeout function.
es5:
setTimeout(function() {b()},100);
es6:
setTimeout(()=> {b()},100);
Upvotes: -1
Reputation: 2998
With new ES6, you can even make it more cleaner and look like sequential,
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
})
}
async function doItHere() {
console.log('a', Date.now());
await delay(5000);
console.log('b', Date.now())
}
doItHere();
Upvotes: 3