Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my setTimeout in (endless) while loop not working? (timer)

I wanted to write a simple timer that counted op by 1 in about one second intervals and
(not knowing about the existence of setInterval)
I wrote this:

let log : boolean = true;

const setLogTrue = () => {
  log = true;
};

let timer : number = 0

while (true){
    if (log == true){
        timer ++;
        console.log(timer);
        log = false;
        setTimeout(setLogTrue, 1000);
    }
}

Is only print out 1 and then waits forever for the log to become true again.

Question: Why is it not setting log back to true?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I cant figure out why my first try is not working.
I cant use the debug terminal cause i cant find where to keep track of the setInterval countdown.

Not the question: How to do it.
It can be done whit setInterval:

let timer : number = 0
const printTimer = () =>{
timer ++;
console.log(timer);

}
setInterval(printTimer, 1000);

or by using setTimeOut in a different way:

const printTimer = () => {
console.log(timer++);
setTimeout(printTimer, 1000);
}
printTimer();

That I know now.

I read In a While loop setTimeout not working.
But that answers a different problem regarding loops and timeout
being: timeout does not pauze the rest of your code.

Does anyone know we I got it wrong? =)

>Solution :

The problem is that you have a while (true).

JavaScript runs on a single thread. Asynchronous callbacks from things like setTimeout or HTTP Requests are placed on a queue, and picked up once the execution thread isn’t actively doing anything. Since your initial while loop never completes, that execution thread never gets released, so there’s never an opportunity for your timeouts to fire.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading