当前位置:网站首页>实现防抖与节流函数
实现防抖与节流函数
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('发起请求')
}边栏推荐
猜你喜欢

STM32(十)------- SPI通信

安装Xshell并使用其进行Ymodem协议的串口传输

The 232-layer 3D flash memory chip is here: the single-chip capacity is 2TB, and the transmission speed is increased by 50%

RecyclerView的高效使用第一节

梅克尔工作室-第一次

基于最小二乘法和SVM从天气预报中预测太阳能发电量(Matlab代码实现)

Jmeter常用的十大组件

格林美瑞交所IPO:募资3.8亿美元 更多中国企业将赴欧洲上市

DBeaver连接MySQL 8.x时Public Key Retrieval is not allowed 错误解决

UnityShader入门学习(二)——渲染流水线
随机推荐
OpenShift 4 - 用 Operator 部署 Redis 集群
Ubantu project 4: xshell, XFTP connected the virtual machine and set xshell copy and paste the shortcut
435. 无重叠区间
QGIS 加载WMS数据,重新投影
Gorm—Go语言数据库框架
Spark学习(2)-Spark环境搭建-Local
思路迪医药冲刺港股:5个月亏2.9亿 泰格医药与先声药业是股东
TRACE32——C源码关联
Excel quickly aligns the middle name of the table (two-word name and three-word name alignment)
c语言hello world代码(代码编程入门)
Asynchronous processing business using CompletableFuture
TRACE32——常用操作
TRACE32——基于SNOOPer的变量记录
2021 OWASP TOP 10 漏洞指南
TRACE32 - C source code association
ASP.NET Core 产生连续 Guid
R语言ggplot2可视化:使用ggpubr包的ggboxplot函数可视化箱图、使用font函数自定义图例标题文本(legend.title)字体的大小、颜色、样式(粗体、斜体)
【CUDA学习笔记】初识CUDA
charles进行弱网测试(app弱网测试怎么做)
如何进行需求分析评审