2

i want this output 1,1,1,....

instead of 2,1

i want to run synchronously

//just wait 2 seconds
function s(callback){
    setTimeout(() => {
        callback()
    }, 2000);
}
a=[2]
while (a.length!==0){
    a.shift()
    s(()=>{
        a.push(2)
        console.log('1');
    })
}
console.log('2');

1 Answers1

2

One way you can achieve this, using your current code, is using async/await and Promises.

//just wait 2 seconds
function s(callback) {
  return new Promise(resolve => {
    setTimeout(() => {
      callback()
      resolve()
    }, 2000);
  })
}

const main = async function() {
  const a = [2];
  while (a.length !== 0) {
    a.shift()
    // This "waits" for s to complete. And s returns a Promise which completes after 2 secs
    await s(() => {
      a.push(2)
      console.log('1');
    })
  }
  console.log('2');
}

main()

If you really just need an infinite loop while(true) { /* ... */ } is enough.

maazadeeb
  • 5,922
  • 2
  • 27
  • 40