7

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);
});
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424

2 Answers2

15

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
10

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')
Roman
  • 19,236
  • 15
  • 93
  • 97
  • Why would I want to make use of a promise here instead of simply using setTimeout()? What are the advantages of using a promise here? – Rishab Gupta Mar 03 '23 at 00:27