Prevent onbeforeunload function when pausing javascript timer

On my webpage, I have a countdown timer using javascript setTimeout() .

  function Tick() { if (RemainingSeconds <= 0) { alert("Time is up."); return; } RemainingSeconds -= 1; ElapsedSeconds += 1; UpdateTimerDisplay(); window.setTimeout("Tick()", 1000); } 

I also have a function running on onbeforeunload to “prevent” a user leaving the page.

  window.onbeforeunload = function () { if (!isIEAjaxRequest) { return "You should use the logout button to leave this page!"; } else { isIEAjaxRequest = false; } }; 

The problem is that when "Are you sure you want to leave this page?" window, it pauses the setTimeout() function. Any thoughts on how to prevent this?

+4
source share
3 answers

A possible workaround would be to use var before = new Date() to store the time until your dialog box appears, and then use it to calculate the elapsed time after your dialog disappears to compensate for missed seconds.

+2
source

You can not. Javascript is strictly single-threaded, so any modal popup pauses everything else.

+4
source

No, you cannot continue to update the user interface in the background while the user interface thread is consumed by another task (in this case, presenting this built-in dialog box).

See Javascript Timeout Specification

+1
source

Source: https://habr.com/ru/post/1437844/


All Articles