模拟定时异步调用



我正在尝试模拟一个异步回调,它在设定的秒数内完成一些操作。我希望这些都能在触发后的3秒内同时登录。现在,他们连续3秒登录。sleep函数阻止了整个脚本的运行。知道为什么吗?

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);
});

使用setTimeout()为将来的时间安排一些事情。

另外,setTimeout()是异步的,循环不是。

var same = function(str, callback){
    setTimeout(function() {
        callback(str);
    }, 3000);
}

注意:不能从异步回调返回值,因为它是异步的。函数same()在实际调用回调之前很久就完成并返回。

使用ES6,您可以使用以下基于辅助延迟函数的技术:

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')

最新更新