The requestIdleCallback function allows you to do work while the browser is idle.

For example, let’s measure how long we’ve waited before the callback has been actually executed:

const now = Date.now(); window.requestIdleCallback(() => console.log('Waited', Date.now() - now, 'ms'))
// Waited 6 ms

requestIdleCallback also allows a timeout to be configured. There is a caveat, though - currently it’s not supported on IE/Edge :)

More information can be found on MDN.