使用RandomTimeOut(Javascript)维护输出顺序

时间:2018-07-26 07:25:59

标签: javascript asynchronous random

此代码将以随机顺序输出1到5。但是,我们希望此代码以顺序方式(1,2,3,4,5)输出。我确实有解决方案,可能不是解决此问题的正确方法。需要想法或正确的解决方案。

'use strict';
const callback = function( result ){
    console.log(result);
};
const print = function( num ){
    for(let i =0 ; i < num ; i++){
        randomTimeout(i , callback);
    }
};
const randomTimeout = function( i , callback ) {
    setTimeout(function(){
        callback('Processing '+ i);
    }, Math.random()*1000 );
};
print(5);

解决方案:

'use strict';
const callback = function( result ){
    console.log(result);
    print(5);
};
let i = 1;
const print = function( num ){
    if(i<=num)
        randomTimeout( i++ , callback );
};
const randomTimeout = function( i , callback ) {
    setTimeout(function(){
        callback('Processing '+ i);
    }, Math.random()*1000 );
};
print(5);

提前谢谢!

1 个答案:

答案 0 :(得分:0)

如果要按顺序开始超时,则在答案中发布的解决方案应该可以正常工作。对于num = 5,您的运行时间平均为2.5秒。

如果要同时开始所有超时,则可以使用Promise.all(),如下例所示。对于num = 5,运行时间平均为0.5秒。

const randomTimeout = (i, callback) => {
  setTimeout(function() {
    callback('Processing ' + i);
  }, Math.random() * 1000);
};

const print = (n, callback) => {
  const values = Array.from({length: 5}, (_, k) => k + 1);
  const promises = values.map(i => new Promise((resolve, reject) => {
    randomTimeout(i, resolve);
  }));
  
  Promise.all(promises).then(result => result.forEach(callback));
}

print(5, x => console.log(x));