Skip to content

Commit 27007ae

Browse files
author
bbc6bae9
committed
主线程创建定时器
1 parent 8dec241 commit 27007ae

File tree

1 file changed

+19
-16
lines changed

1 file changed

+19
-16
lines changed

Category/HONEJSTimer.m

+19-16
Original file line numberDiff line numberDiff line change
@@ -57,29 +57,32 @@ - (long)setTimeout:(JSValue *)callBack :(float)timeout{
5757

5858
#pragma - Private
5959
- (long)createTimer:(JSValue *)callBack ms:(double)ms repeats:(BOOL)repeats{
60+
// 同一事件最多只允许创建 timerSafeMaxCount 个定时器
6061
if ([self.timers allKeys].count > timerSafeMaxCount) {
6162
return timerSafeMaxReachCountIdentifier;
6263
}
63-
long identifier = timerIdentifier;
64-
timerIdentifier += 1;
65-
[self performSelectorOnMainThread:@selector(haha) withObject:nil waitUntilDone:NO];
6664

6765
__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+
});
8083
});
81-
8284
return identifier;
85+
8386
}
8487

8588
-(void)haha{

0 commit comments

Comments
 (0)