iOS 底层原理美文共赏

653,防抖和节流

2021-12-11  本文已影响0人  枫叶1234

了解了新的专业名词:函数防抖、函数节流;虽是第一次知道这个词,但平常开发中其实早已接触使用过了;

防抖与节流是处理频繁事件的技术:用以限制事件频繁地发生可能造成的问题,如:

节流(throttle)

节流是指高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率;

应用场景:
频繁点击按钮只响应一次事件

防抖(debounce

防抖是指触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间;

应用场景:
输入框输入文字时实时搜索功能

节流和防抖的区别

简单来说节流是控制频率,防抖是控制次数
单从字面理解的话,防抖节流容易搞混且不太好理解;下面引用一张图说明:

image.png

以上图基础 举个例子:
Button点击事件有可能存在极短时间内,频繁的点击了多次的情况;针对这种情况分别做节流和防抖处理interval设置为1000ms,实际的效果如下:

iOS实现

知道了思路后,其实不同语言实现起来都不难了;iOS这边可以直接使用dispatch实现(当然也有其他方式)

@implementation MMThrottler

- (instancetype)init {
    self = [super init];
    if (self) {
        _interval = .2;
        _queue = dispatch_get_main_queue();
        _previousDate = NSDate.distantPast;
        _semaphore = dispatch_semaphore_create(1);
    }
    return self;
}

- (void)execute:(void(^)())action {
    __weak typeof(self) selfWeak = self;
    dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
    
    if (_blockItem) {
        // 取消上一次事件
        dispatch_block_cancel(_blockItem);
    }
    
    _blockItem = dispatch_block_create(DISPATCH_BLOCK_BARRIER, ^{
        selfWeak.previousDate = NSDate.date;
        action();
    });
    
    NSTimeInterval seconds = [NSDate.date timeIntervalSinceDate:_previousDate];
    NSTimeInterval delaySeconds = seconds > _interval ? 0 : _interval;
    if (seconds > _interval) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delaySeconds * NSEC_PER_SEC)), _queue, _blockItem);
    }
    
    dispatch_semaphore_signal(_semaphore);
}

@end
@implementation MMDebouncer

- (instancetype)init {
    self = [super init];
    if (self) {
        _interval = .5;
        _queue = dispatch_get_main_queue();
        _semaphore = dispatch_semaphore_create(1);
    }
    return self;
}

- (void)execute:(void(^)())action {
    dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
    
    if (_blockItem) {
        // 取消上一次事件
        dispatch_block_cancel(_blockItem);
    }
    
    _blockItem = dispatch_block_create(DISPATCH_BLOCK_BARRIER, ^{
        action();
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_interval * NSEC_PER_SEC)), _queue, _blockItem);
    
    dispatch_semaphore_signal(_semaphore);
}

@end

上一篇 下一篇

猜你喜欢

热点阅读