iOS中的Throttle(函数节流)与Debounce(函数防抖)

通过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

参考文章:

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容