zoukankan      html  css  js  c++  java
  • throttle(节流)和debounce(防抖)

    防抖和节流都是用来控制频繁调用的问题,但是这两种的应用场景是有区别的。

    throttle(节流)

    有一个调用周期,在一个很长的时间里分为多段,每一段执行一次。例如onscroll,resize,500ms执行一次

    // 使用时间差
    function throttle (fun, wait) {
    	let previous = 0
    
    	return function (...args) {
    		let now = Date.now()
    		let context = this
    		if (now - previous > wait) {
    			fun.apply(context, args)
    			previous = now
    		}
    	}
    }
    
    // 使用定时器
    function throttle1 (func, wait) {
    	let timeout
    	return function (...args) {
    		let context = this
    		if (!timeout) {
    			timeout = setTimeout(function () {
    				timeout = null
    				func.apply(context, args)
    			}, wait)
    		}
    	}
    }
    

    debounce(防抖)

    在一定时间内不调用,只调用一次。例如input事件,停止输入500ms之后再执行。

    function debounce (fun, delay) {
    	let time = null
    	return function (...args) {
    		let ctx = this
    		clearTimeout(time)
    		time = setTimeout(function () {
    			fun.apply(ctx, args)
    			time = null
    		}, delay)
    	}
    }
    
  • 相关阅读:
    C# 多态性
    C# FileStream类
    C# File文件类
    加快访问GitHub的速度
    Git-修改.gitignore后使其配置生效的方法总结
    ES6 解构赋值
    avue表单数据请求
    uniapp canvas组件复用
    uniappH5 fly.js Golang 解决跨域问题
    java bug记录
  • 原文地址:https://www.cnblogs.com/Juliana1992/p/10332938.html
Copyright © 2011-2022 走看看