通过OC实现的两个函数
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, copy) void(^bounceAction)(void);
@property (nonatomic, copy) void(^throttlAction)(void);
@property (nonatomic, copy) void(^bounceThrottlAction)(void);
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.bounceAction = [self getDebounceActionWithTimeInteval:1 action:^{
NSLog(@"Debounce Action");
}];
self.throttlAction = [self getThrottleActionWithTimeInteval:1 action:^{
NSLog(@"Throttle action");
}];
self.bounceThrottlAction = [self getActionWithDebounceTimeInteval:1 ThrottleInteval:1 action:^{
NSLog(@"Throttle and Debounce action");
}];
}
- (void(^)(void))getDebounceActionWithTimeInteval:(double)timeInteval action:(void(^)(void))action {
__block NSInteger index = 0;
return ^{
index ++;
NSInteger inde = index;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeInteval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (inde == index) {
action();
}
});
};
}
- (void(^)(void))getThrottleActionWithTimeInteval:(double)timeInteval action:(void(^)(void))action {
__block NSInteger index = 0;
return ^{
if (index == 0) {
index ++;
} else {
return;
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeInteval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
index = 0;
action();
});
};
}
- (void(^)(void))getActionWithDebounceTimeInteval:(double)debounceTimeInteval
ThrottleInteval:(double)throttleInteval
action:(void(^)(void))action
{
__block NSInteger index = 0;
__block double waitTimeInteval = 0;
return ^{
index ++;
NSInteger asyncBlockInde = index;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(debounceTimeInteval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (asyncBlockInde == index) {
waitTimeInteval = 0;
action();
} else if (waitTimeInteval >= throttleInteval) {
action();
index = -1;
waitTimeInteval = 0;
} else {
waitTimeInteval += debounceTimeInteval;
}
});
};
};
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
self.bounceThrottlAction();
}
@end
参考文章: