| 1 |
let doc, HIDDEN, VISIBILITY_CHANGE, |
| 2 |
nextId = 1; |
| 3 |
const clearHandles = Object.create( null ); |
| 4 |
|
| 5 |
function init( overrideDoc ) { |
| 6 |
doc = overrideDoc || document; |
| 7 |
|
| 8 |
if ( doc.hidden !== undefined ) { |
| 9 |
HIDDEN = 'hidden'; |
| 10 |
VISIBILITY_CHANGE = 'visibilitychange'; |
| 11 |
} else if ( doc.mozHidden !== undefined ) { |
| 12 |
HIDDEN = 'mozHidden'; |
| 13 |
VISIBILITY_CHANGE = 'mozvisibilitychange'; |
| 14 |
} else if ( doc.webkitHidden !== undefined ) { |
| 15 |
HIDDEN = 'webkitHidden'; |
| 16 |
VISIBILITY_CHANGE = 'webkitvisibilitychange'; |
| 17 |
} |
| 18 |
} |
| 19 |
|
| 20 |
init(); |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
module.exports = { |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
set: function ( fn, delay ) { |
| 42 |
let nativeId = null, |
| 43 |
lastStartedAt = mw.now(); |
| 44 |
const visibleId = nextId++; |
| 45 |
|
| 46 |
function clearHandle() { |
| 47 |
if ( nativeId !== null ) { |
| 48 |
clearTimeout( nativeId ); |
| 49 |
nativeId = null; |
| 50 |
} |
| 51 |
delete clearHandles[ visibleId ]; |
| 52 |
if ( VISIBILITY_CHANGE ) { |
| 53 |
|
| 54 |
doc.removeEventListener( VISIBILITY_CHANGE, visibilityCheck, false ); |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
function onComplete() { |
| 59 |
clearHandle(); |
| 60 |
fn(); |
| 61 |
} |
| 62 |
|
| 63 |
function visibilityCheck() { |
| 64 |
const now = mw.now(); |
| 65 |
|
| 66 |
if ( HIDDEN && doc[ HIDDEN ] ) { |
| 67 |
if ( nativeId !== null ) { |
| 68 |
|
| 69 |
delay = Math.max( 0, delay - Math.max( 0, now - lastStartedAt ) ); |
| 70 |
if ( delay === 0 ) { |
| 71 |
onComplete(); |
| 72 |
} else { |
| 73 |
|
| 74 |
clearTimeout( nativeId ); |
| 75 |
nativeId = null; |
| 76 |
} |
| 77 |
} |
| 78 |
} else { |
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
if ( nativeId === null ) { |
| 83 |
lastStartedAt = now; |
| 84 |
nativeId = setTimeout( onComplete, delay ); |
| 85 |
} |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
clearHandles[ visibleId ] = clearHandle; |
| 90 |
if ( VISIBILITY_CHANGE ) { |
| 91 |
doc.addEventListener( VISIBILITY_CHANGE, visibilityCheck, false ); |
| 92 |
} |
| 93 |
visibilityCheck(); |
| 94 |
|
| 95 |
return visibleId; |
| 96 |
}, |
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
clear: function ( visibleId ) { |
| 107 |
if ( visibleId in clearHandles ) { |
| 108 |
clearHandles[ visibleId ](); |
| 109 |
} |
| 110 |
} |
| 111 |
}; |
| 112 |
|
| 113 |
if ( window.QUnit ) { |
| 114 |
module.exports.init = init; |
| 115 |
} |