Launch an action from setInterval when tab is hidden

Viewed 253

Chrome has announced that its new version will throttle timers even more. What is the recommended way in which I can guarantee that a specific action (API request) is called after X milliseconds if the tab is still active but hidden?

1 Answers

The wait function I said is like

function wait(timeoutInMilliseconds, waitConditionFunc, interval=50) {
    const date = new Date();
    if (timeoutInMilliseconds > 0) {
        date.setMilliseconds(date.getMilliseconds() + timeoutInMilliseconds);
    }
    return new Promise((resolve, reject) => {
        if (!waitConditionFunc || !waitConditionFunc()) {
            //if there is no condition, or after checking the condition, we don't need to wait, resolve
            resolve();
        }

        //check the condition intervally until the condition func indicates that we don't need to wait, or time out
        let intervalId = setInterval(() => {
            if (!waitConditionFunc || !waitConditionFunc()) {
                //if there is no condition, or after checking the condition, we don't need to wait, resolve
                clearInterval(intervalId);
                resolve();
            }
            if (timeoutInMilliseconds > 0 && Date.now() >= date) {
                //time out
                clearInterval(intervalId);
                reject("timeout");
            }
        }, interval);
    });
}

You can call the wait by passing say 3600000 (1 hour, or passing 0 for no timeout), and the function of validating the form (or passing null for just waiting for 1 hour). Hope I didn't misunderstand your question and this function helps.

Related