当前位置:网站首页>实现防抖与节流函数
实现防抖与节流函数
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('发起请求')
}
边栏推荐
- OAuth2:微服务权限校验Session共享
- TRACE32——C源码关联
- Trigonometric identity transformation formula
- Sentinel服务熔断和降级
- R语言ggplot2可视化:使用ggpubr包的ggmaplot函数可视化MA图(MA-plot)、font.legend参数和font.main参数设置标题和图例字体加粗
- R language ggplot2 visualization: use the ggmapplot function of the ggpubr package to visualize the MA plot (MA-plot), the font.legend parameter and the font.main parameter to set the title and legend
- 大健云仓冲刺美股:增营收反减利润 京东与DCM是股东
- Recommendation System - Recall Phase - 2013: DSSM (Twin Towers Model) [Embedding (Semantic Vector) Recall] [Microsoft]
- 消息队列消息数据存储MySQL表设计
- Efficient use of RecyclerView Section 2
猜你喜欢
随机推荐
Nuget package and upload tutorial
PDF 拆分/合并
Female service community product design
The 232-layer 3D flash memory chip is here: the single-chip capacity is 2TB, and the transmission speed is increased by 50%
OpenShift 4 - 用 Operator 部署 Redis 集群
为什么毕业季不要表白?
The R language ggstatsplot package ggbarstats function visualizes bar charts, and adds hypothesis test results (including sample number, statistics, effect size and its confidence interval, significan
UnityShader入门学习(二)——渲染流水线
Node实现数据加密
R语言检验样本是否符合正态性(检验样本是否来自一个正态分布总体):shapiro.test函数检验样本是否符合正态分布(normality test)
ASP.NET Core 产生连续 Guid
Ubantu project 4: xshell, XFTP connected the virtual machine and set xshell copy and paste the shortcut
Gorm—Go language database framework
华医网冲刺港股:5个月亏2976万 红杉与姚文彬是股东
Five dimensions to start MySQL optimization
如何进行需求分析评审
NPM Taobao mirror (latest version) released a new version of npm mirror at 2021-11-21 16:53:52 [easy to understand]
R语言ggplot2可视化:使用ggpubr包的ggmaplot函数可视化MA图(MA-plot)、font.legend参数和font.main参数设置标题和图例字体加粗
/etc/profile、/etc/bashrc、~/.bash_profile、~/.bashrc 文件的作用
The meaning of node_exporter performance monitoring information collection in Prometheus