I'm trying to simulate an async callback, that does something in a set number of seconds. I want these to all log at the same time, 3 seconds from when they are triggered. Right now they log consecutively 3 seconds after each other. The sleep functions are blocking the whole script from running. Any idea why?
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
var same = function(string, callback) {
new sleep(3000);
return callback(string);
}
same("same1", function(string) {
console.log(string);
});
same("same2", function(string) {
console.log(string);
});
same("same3", function(string) {
console.log(string);
});
Use setTimeout()
to schedule something for a future time.
Also, setTimeout()
is async, your looping is not.
var same = function(str, callback){
setTimeout(function() {
callback(str);
}, 3000);
}
Note: you cannot return a value from the async callback because it's async. The function same()
completes and returns long before the callback is actually called.
With ES6, you can use the following technique based on an helper delay function:
const delay = async (delay = 1000, callback = () => {}) => {
const delayPromise = ms => new Promise(res => setTimeout(res, ms))
await delayPromise(delay)
callback()
}
const funcCallback = () => { console.info('msg WITH delay > 2') }
delay(5000, funcCallback)
console.info('Instant msg > 1')
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