模拟定时异步调用

Tho*_*ggi 3 javascript sleep asynchronous

我正在尝试模拟异步回调,它在一定的秒数内完成.我希望这些都能同时记录,从触发它们起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);
});
Run Code Online (Sandbox Code Playgroud)

jfr*_*d00 11

使用setTimeout()安排的东西今后一段时间.

此外,setTimeout()是异步,你的循环不是.

var same = function(str, callback){
    setTimeout(function() {
        callback(str);
    }, 3000);
}
Run Code Online (Sandbox Code Playgroud)

注意:您无法从异步回调中返回值,因为它是异步的.该函数same()在实际调用回调之前完成并返回很长时间.


Rom*_*man 8

使用 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')
Run Code Online (Sandbox Code Playgroud)