This code will output 1 to 5 in random order. However, we want this code to output in the sequential manner (1,2,3,4,5). I do have a solution which may not be the right way to approach this question. Need Thoughts or right solution.
'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);
Solution:
'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);
Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire