Devs, I have a timer that freezes when it runs beforeunload
when trying to change direction or refresh the page. When the prompt is canceled the timer continues. But that's not the behavior I expect.
I hope that even if the stopwatch prompt appears, it beforeunload
continues to count...
The timer works with useEffect and useRef, normal.
And here is my usage of beforeunload
:
useEffect(() => {
const handleBeforeUnload = (event) => event.preventDefault();
if (checkTestState(TEST_STATES.IN_PROCESS)) {
window.addEventListener('beforeunload', handleBeforeUnload);
} else {
window.removeEventListener('beforeunload', handleBeforeUnload);
}
return () => window.removeEventListener('beforeunload', handleBeforeUnload);
});
What you want is impossible .
The way Javascript works, the events of
setTimeout( )
orsetInterval( )
depend on the language's event loop being executed. They depend on only asynchronous tasks being performed .Any synchronous task ( prompt , synchronous AJAX operations, ...) stops the event loop, so any
setTimeout( )
osetInterval( )
stops executing until the event loop resumes.An alternative is to use
Date.now( )
to control real time, whether or not you are in the event loop:The above code displays a message. If you click on aceptar:
Within 5 seconds, the
alert( )
is displayed at the set time, 5 seconds after the start of execution.After 5 seconds have elapsed, the
alert( )
is displayed as soon as the is leftmessage( )
.