@@ -57,29 +57,32 @@ - (long)setTimeout:(JSValue *)callBack :(float)timeout{
57
57
58
58
#pragma - Private
59
59
- (long )createTimer : (JSValue *)callBack ms : (double )ms repeats : (BOOL )repeats {
60
+ // 同一事件最多只允许创建 timerSafeMaxCount 个定时器
60
61
if ([self .timers allKeys ].count > timerSafeMaxCount) {
61
62
return timerSafeMaxReachCountIdentifier;
62
63
}
63
- long identifier = timerIdentifier;
64
- timerIdentifier += 1 ;
65
- [self performSelectorOnMainThread: @selector (haha ) withObject: nil waitUntilDone: NO ];
66
64
67
65
__block NSTimeInterval interval = ms / 1000.0 ;
68
- NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: interval target: self selector: @selector (action: ) userInfo: callBack repeats: repeats];
69
- NSString *keyStr = [NSString stringWithFormat: @" %ld " , identifier];
70
- NSLog (@" [createTimer] keyStr =%@ ms=%f " , keyStr, ms);
71
- self.timers [keyStr] = timer;
72
- // 超时保护
73
- dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t )(timerSafeMaxTime * NSEC_PER_MSEC)), dispatch_get_main_queue (), ^{
74
- if ([[self .timers allKeys ] containsObject: keyStr]){
75
- NSLog (@" 【超时保护】发现超过安全时间的定时器:%@ ,自动清除" , keyStr);
76
- [self clearTimeout: [keyStr longLongValue ]];
77
- }else {
78
- NSLog (@" 【超时保护】没有发现超过安全时间的定时器" );
79
- }
66
+ __block long identifier = timerIdentifier;
67
+ timerIdentifier += 1 ;
68
+ dispatch_async (dispatch_get_main_queue (), ^{
69
+ NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: interval target: self selector: @selector (action: ) userInfo: callBack repeats: repeats];
70
+ NSString *keyStr = [NSString stringWithFormat: @" %ld " , identifier];
71
+ NSLog (@" [createTimer] keyStr =%@ ms=%f " , keyStr, ms);
72
+ self.timers [keyStr] = timer;
73
+
74
+ // 超时保护
75
+ dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t )(timerSafeMaxTime * NSEC_PER_MSEC)), dispatch_get_main_queue (), ^{
76
+ if ([[self .timers allKeys ] containsObject: keyStr]){
77
+ NSLog (@" 【超时保护】发现超过安全时间的定时器:%@ ,自动清除" , keyStr);
78
+ [self clearTimeout: [keyStr longLongValue ]];
79
+ }else {
80
+ NSLog (@" 【超时保护】没有发现超过安全时间的定时器" );
81
+ }
82
+ });
80
83
});
81
-
82
84
return identifier;
85
+
83
86
}
84
87
85
88
-(void )haha {
0 commit comments