0

I want to send analytics data to server at low priority. My function is:

const schedule_serversync = function (deadline) {
    if (deadline.timeRemaining() > 0) {
        server_sync(); //async ajax call of approx few ms duration
    }
    requestIdleCallback(schedule_serversync, { timeout: 60000 });
}

As soon as I call requestIdleCallback(schedule_serversync, { timeout: 60000 }); from onload, schedule_serversync is called immediately and the requests go into infinite tight loop. This happens even if the window is not idle (I'm clicking, moving mouse etc, but the callbacks continue).

I know I can break the tight loop using setTimeout while rescheduling requestIdleCallback.

My question is - shouldn't schedule_serversync be called only when browser is idle with max delay of 60 seconds? What defines idle here? I was expecting it to be fired when user moves to some other browser tab or window. Is there a way I can set minimum delay (other than using setTimeout of my own)?

5
  • You're not checking the didTimeout flag on the deadline object. Commented Oct 25, 2023 at 20:50
  • 1
    You might also want to look into sendBeacon, it seems like it might be closer to what you want. Commented Oct 25, 2023 at 20:51
  • Also "idle" means "not running any event loops". If you're sitting there just staring at the page, the browser is idle. Commented Oct 25, 2023 at 20:55
  • 2
    I think you misunderstand how the timeout is used. It doesn't mean "idle for 60 seconds". It means "queue the function in 60 seconds even if we've never been idle". Your code will run in a tight loop whenever the browser is idle. Commented Oct 25, 2023 at 21:01
  • 1
    What you might want to do is use setInterval() to periodically call requestIdleCallback(). Commented Oct 25, 2023 at 21:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.