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?
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.