当前位置:网站首页>实现防抖与节流函数
实现防抖与节流函数
2022-07-31 15:03:00 【墨明棋妙Mi】
什么是节流
规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行
1.定时器
let box = document.querySelector( ".box")
box.addEventListener( "touchmove", throttle(demo,2000))
function throttle(event,time){
let timer = null
return function(){
if(!timer) {
timer = setTimeout(() =>{
event();
timer = null;
}, time);
}
}
}
function demo(){
console.log('发起请求')
}2.时间戳
var throttle = function(fn, delay) {
var prev = Date.now();
return function() {
var context = this;
var args = arguments;
var now = Date.now();
if (now - prev >= delay) {
fn.apply(context, args);
prev = Date.now();
}
}
}
function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));什么是防抖
当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。
let telInput = document.querySelector( 'input' )
telInput.addEventListener( 'input' , antiShake(demo,2000))
//防抖封装
function antiShake(fn,wait){
let timeOut = null;
return args =>{
if(timeout) clearTimeout(timeOut)
timeOut = setTimeout(fn, wait);
}
}
function demo(){
console.log('发起请求')
}边栏推荐
- 2021 OWASP TOP 10 漏洞指南
- DBeaver连接MySQL 8.x时Public Key Retrieval is not allowed 错误解决
- sentinel与nacos持久化
- Ubantu专题4:xshell、xftp连接接虚拟机以及设置xshell复制粘贴快捷键
- element-plus虚拟表格virtual-list组件中是怎么实现清理lodash.memoize缓存的?
- RecyclerView高效使用第三节
- WeChat chat record search in a red envelope
- Unity Shader入门精要学习——透明效果
- Groupid(artifact id)
- 模板与泛型编程值typelist实现
猜你喜欢
随机推荐
华医网冲刺港股:5个月亏2976万 红杉与姚文彬是股东
Introductory UnityShader learning (2) - the rendering pipeline
LeetCode二叉树系列——222.完全二叉树的节点个数
redhat/openssl generates a self-signed ca certificate and uses it
微信聊天记录中搜索红包
【CUDA学习笔记】初识CUDA
网线RJ45接口针脚[通俗易懂]
How to grab configuration information for DELL SC compellent storage system
高等数学——常用不定积分公式
[CUDA study notes] First acquaintance with CUDA
安装Xshell并使用其进行Ymodem协议的串口传输
最小费用最大流问题详解
RecyclerView高效使用第二节
49. The copy constructor and overloaded 】
R language ggplot2 visualization: use the ggboxplot function of the ggpubr package to visualize the grouped box plot, use the ggpar function to change the graphical parameters (caption, add, modify th
SetoolKit User Guide
PDF 拆分/合并
Message queue data storage MySQL table design
LeetCode二叉树系列——110.平衡二叉树
R语言向前或者向后移动时间序列数据(自定义滞后或者超前的期数):使用dplyr包中的lag函数将时间序列数据向前移动一天(设置参数n为正值)









