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

5
  • This is running synchronously. setTimeout doesnot mean code is running asynchronously Commented Apr 13, 2019 at 12:50
  • This problem might be already resolved there: stackoverflow.com/questions/4122268/… Commented Apr 13, 2019 at 12:55
  • Do you want an infinite loop printing 1? Commented Apr 13, 2019 at 13:04
  • It is unclear why the array even exists here a=[2], it would be interesting to know the reason for that -although not part of the problem it seems. Commented Apr 13, 2019 at 13:29
  • As a infinite loop this may eventually pop an error in modern browsers that detect that. Commented Apr 13, 2019 at 13:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.