0

const x = {value: 1};

function plus(obj){
    setTimeout(() => {
        obj.value++; 
        console.log("timeout...");
    }, 3000);
};

plus(x)

setInterval(()=>{
    if(x.value==1){
       console.log(`x=${x.value}`);
    }
},500)


//while(x.value == 1){
//    console.log(`not yet!! x = ${x.value}`)
//}

The function plus adds 1 after 5 sec and setInterval keep print log until x.value is not 1.

It works as I intended.

But while loop which I annotated prints log infinity.

I can't find any difference between setInterval and while except setInterval do this every 0.5 sec.

Can anyone explain why while loop never ends?

( I think while loop should end after 3 secs because the function plus changes value of x by adding 1, so condition in while loop is false after 3 secs )

BeGood
  • 11
  • 4

0 Answers0