1 | var assert = require('assert')
|
2 |
|
3 | var dftOpts = {}
|
4 | var hasWindow = typeof window !== 'undefined'
|
5 | var hasIdle = hasWindow && window.requestIdleCallback
|
6 |
|
7 | module.exports = onIdle
|
8 |
|
9 | function 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 |
|
19 |
|
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 | }
|