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));
  • 相关阅读:
    ABAP 表格控制(Table Control)和步循环
    ABAP中正则表达式的简单使用方法 (转老白BLOG)
    ABAP常用函数集锦
    ALV用例大全
    DXP 笔记
    STM32笔记——Power Controller(PWR)
    STM32之glossary
    STM32 解析futaba S-bus协议
    Windows下 vundle的安装和使用
    使用串口绘制实时曲线 —— SerialChart
  • 原文地址:https://www.cnblogs.com/wangsai-666/p/11977592.html
Copyright © 2011-2022 走看看