Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate a timed async call

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);
});
like image 778
ThomasReggi Avatar asked Nov 30 '22 02:11

ThomasReggi


2 Answers

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.

like image 64
jfriend00 Avatar answered Dec 02 '22 17:12

jfriend00


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')
like image 45
Roman Avatar answered Dec 02 '22 17:12

Roman