UNPKG

925 BJavaScriptView Raw
1var assert = require('assert')
2
3var dftOpts = {}
4var hasWindow = typeof window !== 'undefined'
5var hasIdle = hasWindow && window.requestIdleCallback
6
7module.exports = onIdle
8
9function onIdle (cb, opts) {
10 opts = opts || dftOpts
11 var timerId
12
13 assert.equal(typeof cb, 'function', 'on-idle: cb should be type function')
14 assert.equal(typeof opts, 'object', 'on-idle: opts should be type object')
15
16 if (hasIdle) {
17 timerId = window.requestIdleCallback(function (idleDeadline) {
18 // reschedule if there's less than 10ms remaining on the tick
19 // and a timer did not expire
20 if (idleDeadline.timeRemaining() <= 10 && !idleDeadline.didTimeout) {
21 return onIdle(cb, opts)
22 } else {
23 cb(idleDeadline)
24 }
25 }, opts)
26 return window.cancelIdleCallback.bind(window, timerId)
27 } else if (hasWindow) {
28 timerId = setTimeout(cb, 0)
29 return clearTimeout.bind(window, timerId)
30 }
31}