当前位置:网站首页>实现防抖与节流函数
实现防抖与节流函数
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('发起请求')
}边栏推荐
- 学习笔记12--路径-速度分解法之局部路径搜索
- Ubuntu Topic 5: Setting a Static IP Address
- NPM Taobao mirror (latest version) released a new version of npm mirror at 2021-11-21 16:53:52 [easy to understand]
- Trigonometric identity transformation formula
- Word table to Excel
- "Listen to me, thank you" can be said in ancient poetry?Tsinghua University has developed an artifact of "Searching Sentences According to Meaning", which can search for the famous sayings you want wi
- 基于最小二乘法和SVM从天气预报中预测太阳能发电量(Matlab代码实现)
- Network cable RJ45 interface pins [easy to understand]
- Nuget打包并上传教程
- Web自动化实战——Selenium4(自动化测试环境的搭建)
猜你喜欢
随机推荐
Unity Shader入门精要学习——透明效果
DeepLab Series Learning
谷歌CTS测试(cta测试)
R语言ggplot2可视化:使用ggpubr包的ggboxplot函数可视化箱图、使用font函数自定义图例标题文本(legend.title)字体的大小、颜色、样式(粗体、斜体)
Synchronized和volatile 面试简单汇总
Sentinel限流和异常处理
MANIFEST.MF文件(PDB文件)
小试牛刀:Go 反射帮我把 Excel 转成 Struct
Advanced Mathematics - Commonly Used Indefinite Integral Formulas
Jmeter常用的十大组件
《微信小程序-进阶篇》Lin-ui组件库源码分析-Icon组件
名创优品斥资6.95亿购买创始人叶国富所持办公楼股权
sentinel与nacos持久化
SQL、HQL、JPQL 到底有什么区别
Prometheus之node_exporter性能监控信息采集含义
Ubantu专题5:设置静态ip地址
Excel快速对齐表格的中姓名(两个字姓名和三个字姓名对齐)
TRACE32 - SNOOPer-based variable logging
The 232-layer 3D flash memory chip is here: the single-chip capacity is 2TB, and the transmission speed is increased by 50%
DBeaver连接MySQL 8.x时Public Key Retrieval is not allowed 错误解决









