zoukankan      html  css  js  c++  java
  • 节流和防抖

    节流 throttle

    节流(throttle):当持续触发事件时,保证一定时间段内只调用一次事件处理函数。

    函数节流主要有两种实现方法:时间戳和定时器。

     var throttle = function(func, delay) {
        var prev = Date.now();
        return function() {
            var context = this;
            var args = arguments;
            var now = Date.now();
            if (now - prev >= delay) {
                func.apply(context, args);
                prev = Date.now();
            }
        }
    }
    function handle() {
        console.log(Math.random());
    }
    window.addEventListener('scroll', throttle(handle, 1000));
     

    当高频事件触发时,第一次会立即执行(给scroll事件绑定函数与真正触发事件的间隔一般大于delay),而后再怎么频繁地触发事件,也都是每delay时间才执行一次。而当最后一次事件触发完毕后,事件也不会再被执行了

     
     var throttle = function(func, delay) {
        var timer = null;
        return function() {
            var context = this;
            var args = arguments;
            if (!timer) {
                timer = setTimeout(function() {
                    func.apply(context, args);
                    timer = null;
                }, delay);
            }
        }
    }
    function handle() {
        console.log(Math.random());
    }
    window.addEventListener('scroll', throttle(handle, 1000));
     

    防抖 debounce

    防抖(debounce):当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。

     
     
     
     
     
     
    function debounce(fn, wait) {
        var timeout = null;
        return function() {
            if(timeout !== null) 
                clearTimeout(timeout);
            timeout = setTimeout(fn, wait);
        }
    }
    // 处理函数
    function handle() {
        console.log(Math.random()); 
    }
    // 滚动事件
    window.addEventListener('scroll', debounce(handle, 1000));
  • 相关阅读:
    flutter 中 List 和 Map 的用法
    AndroidStudio中Flutter打包APK
    flutter中的异步机制 Future
    [控件] 画饼状图的控件
    用CAShapeLayer写股市K线图动画效果
    使用Instruments中的CoreAnimation分析动画
    山寨Facebook的Shimmer效果
    maskView遮罩中多张图片的动画
    将CAGradientLayer用作maskView的遮罩图层
    [翻译] JKLLockScreenViewController
  • 原文地址:https://www.cnblogs.com/wangsai-666/p/11977592.html
Copyright © 2011-2022 走看看