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));
  • 相关阅读:
    【js】实现输入框不允许输入某些特殊字符
    springboot集成druid实现数据源监控
    SpringBoot整合Druid并配置数据源监控
    SpringBoot集成Druid实现数据源管理和监控
    同一个catch字句中捕获多个java异常
    【JWT】JSON Web Token原理与实现
    行级锁实验:sql语句条件中的索引对锁的影响
    什么是乐观锁,什么是悲观锁,如何实现
    Linux命令与文件的查找which、wheris、locate、find
    vi编辑器永久设置行号、缩进
  • 原文地址:https://www.cnblogs.com/wangsai-666/p/11977592.html
Copyright © 2011-2022 走看看