Skip to content

Commit

Permalink
refactor: update appJS.setTimeoutFocusDependent()
Browse files Browse the repository at this point in the history
  • Loading branch information
winternet-studio committed Sep 10, 2023
1 parent 9fce61f commit 73376c2
Showing 1 changed file with 7 additions and 10 deletions.
17 changes: 7 additions & 10 deletions assets/JsHelper/JsHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -993,8 +993,7 @@ appJS.systemMsg = {
/**
* Set a timeout but only execute it when browser tab has focused
*
* NOTE: as is this cannot coexist together with other `window.onblur` and `window.onfocus` handlers.
* Tried using `window.addEventListener('blur')` but it didn't work, which is confirmed by {@link https://stackoverflow.com/questions/11955774/javascript-window-addeventlistenerblur-wont-work Javascript, window.addEventListener('blur') won't work}
* Can use `document.hasFocus()` at any time to check current status.
*
* @param {callable} callback : Function to call on timeout
* @param {integer} duration : Milliseconds after which the earliest possible call to the function should be.
Expand All @@ -1004,22 +1003,20 @@ appJS.setTimeoutFocusDependent = function(callback, duration) {
var hasFocus = true;
var skippedDueToNotFocused = false;

if (window.onblur || window.onfocus) {
alert('Cant set focus-dependent timeout because another onblur or onfocus handler has already been set.');
}

window.onblur = function() {
var blurHandler = function() {
hasFocus = false;
};
window.onfocus = function() {
var focusHandler = function() {
if (skippedDueToNotFocused) {
callback();
window.onblur = null;
window.onfocus = null;
window.removeEventListener('blur', blurHandler);
window.removeEventListener('focus', focusHandler);
return;
}
hasFocus = true;
};
window.addEventListener('blur', blurHandler);
window.addEventListener('focus', focusHandler);

setTimeout(function() {
if (hasFocus) {
Expand Down

0 comments on commit 73376c2

Please sign in to comment.