当前位置:网站首页>实现防抖与节流函数
实现防抖与节流函数
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('发起请求')
}
边栏推荐
- 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
- 基于极限学习机(ELM)进行多变量用电量预测(Matlab代码实现)
- Spark学习(2)-Spark环境搭建-Local
- 使用 PyTorch 检测眼部疾病
- 使用 Chainlink Keepers 实现智能合约函数的自动化执行
- Network cable RJ45 interface pins [easy to understand]
- 自适应控制——仿真实验三 用超稳定性理论设计模型参考自适应系统
- LeetCode二叉树系列——226.翻转二叉树
- [CUDA study notes] First acquaintance with CUDA
- 【CUDA学习笔记】初识CUDA
猜你喜欢
How to grab configuration information for DELL SC compellent storage system
Getting started with UnityShader (1) - GPU and Shader
Excel快速对齐表格的中姓名(两个字姓名和三个字姓名对齐)
Description of Hikvision camera streaming RTSP address rules
Female service community product design
TCP详解
NC | 斯坦福申小涛等开发数据可重复分析计算框架TidyMass
《微信小程序-进阶篇》Lin-ui组件库源码分析-Icon组件
The 232-layer 3D flash memory chip is here: the single-chip capacity is 2TB, and the transmission speed is increased by 50%
2021 OWASP TOP 10 漏洞指南
随机推荐
The use of thread pool two
Getting started with UnityShader (3) - Unity's Shader
TRACE32 - Common Operations
Sentinel服务熔断和降级
微服务架构选型
Synchronized and volatile interview brief summary
/etc/profile、/etc/bashrc、~/.bash_profile、~/.bashrc 文件的作用
R语言ggplot2可视化:使用ggpubr包的ggboxplot函数可视化箱图、使用font函数自定义图例标题文本(legend.title)字体的大小、颜色、样式(粗体、斜体)
UnityShader入门学习(一)——GPU与Shader
OAuth2:四种授权方式
乡村基冲刺港交所:5个月期内亏2224万 SIG与红杉中国是股东
SQL、HQL、JPQL 到底有什么区别
R语言的画图代码及差异性分析[通俗易懂]
Redis与分布式:主从复制
三角恒等变换公式
Sentinel安装与部署
TCP详解
C language basic practice (nine-nine multiplication table) and printing different asterisk patterns
Use of el-tooltip
RecyclerView的高效使用第一节