@@ -18,21 +18,50 @@ import {findEventTask, patchMacroTask, patchMicroTask} from '../common/utils';
18
18
19
19
const set = 'set' ;
20
20
const clear = 'clear' ;
21
- const _global = typeof window === 'object' && window || typeof self === 'object' && self || global ;
22
21
23
22
Zone . __load_patch ( 'timers' , ( global : any , Zone : ZoneType , api : _ZonePrivate ) => {
24
23
// Timers
25
- const timers = require ( 'timers' ) ;
26
- patchTimer ( timers , set , clear , 'Timeout' ) ;
27
- patchTimer ( timers , set , clear , 'Interval' ) ;
28
- patchTimer ( timers , set , clear , 'Immediate' ) ;
29
-
30
- const shouldPatchGlobalTimers = global [ 'setTimeout' ] !== timers . setTimeout ;
24
+ let globalUseTimeoutFromTimer = false ;
25
+ try {
26
+ const timers = require ( 'timers' ) ;
27
+ let globalEqualTimersTimeout = global . setTimeout === timers . setTimeout ;
28
+ if ( ! globalEqualTimersTimeout ) {
29
+ // if global.setTimeout not equal timers.setTimeout, check
30
+ // whether global.setTimeout use timers.setTimeout or not
31
+ const originSetTimeout = timers . setTimeout ;
32
+ timers . setTimeout = function ( ) {
33
+ globalUseTimeoutFromTimer = true ;
34
+ return originSetTimeout . apply ( this , arguments ) ;
35
+ } ;
36
+ const detectTimeout = global . setTimeout ( noop , 100 ) ;
37
+ clearTimeout ( detectTimeout ) ;
38
+ timers . setTimeout = originSetTimeout ;
39
+ }
40
+ if ( globalUseTimeoutFromTimer ) {
41
+ // global use timers setTimeout, but not equals
42
+ // this happenes when use nodejs v0.10.x, global setTimeout will
43
+ // use a lazy load version of timers setTimeout
44
+ // we should not double patch timer's setTimeout
45
+ // so we only store the __symbol__ for consistency
46
+ global [ Zone . __symbol__ ( 'setTimeout' ) ] = global . setTimeout ;
47
+ global [ Zone . __symbol__ ( 'setInterval' ) ] = global . setInterval ;
48
+ global [ Zone . __symbol__ ( 'setImmediate' ) ] = global . setImmediate ;
49
+ }
31
50
32
- if ( shouldPatchGlobalTimers ) {
33
- patchTimer ( _global , set , clear , 'Timeout' ) ;
34
- patchTimer ( _global , set , clear , 'Interval' ) ;
35
- patchTimer ( _global , set , clear , 'Immediate' ) ;
51
+ patchTimer ( timers , set , clear , 'Timeout' ) ;
52
+ patchTimer ( timers , set , clear , 'Interval' ) ;
53
+ patchTimer ( timers , set , clear , 'Immediate' ) ;
54
+ } catch ( error ) {
55
+ // timers module not exists, for example, when we using nativescript
56
+ // timers is not available
57
+ }
58
+ if ( ! globalUseTimeoutFromTimer ) {
59
+ // 1. global setTimeout equals timers setTimeout
60
+ // 2. or global don't use timers setTimeout(maybe some other library patch setTimeout)
61
+ // 3. or load timers module error happens, we should patch global setTimeout
62
+ patchTimer ( global , set , clear , 'Timeout' ) ;
63
+ patchTimer ( global , set , clear , 'Interval' ) ;
64
+ patchTimer ( global , set , clear , 'Immediate' ) ;
36
65
}
37
66
} ) ;
38
67
0 commit comments