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