当前位置:网站首页>实现防抖与节流函数
实现防抖与节流函数
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('发起请求')
}边栏推荐
- 女性服务社群产品设计
- TCP详解
- OpenShift 4 - Customize RHACS security policies to prevent production clusters from using high-risk registry
- TRACE32——基于SNOOPer的变量记录
- Word表格转到Excel中
- Essential Learning for Getting Started with Unity Shader - Transparency Effect
- R语言ggstatsplot包ggbarstats函数可视化条形图、并添加假设检验结果(包含样本数、统计量、效应大小及其置信区间、显著性、组间两两比较、贝叶斯假设)、检验结果报告符合APA标准
- abaqus find contact pairs报错:surface name is already in use
- STM32(十)------- SPI通信
- 435. 无重叠区间
猜你喜欢

Redis与分布式:哨兵模式

《微信小程序-进阶篇》Lin-ui组件库源码分析-Icon组件

Sentinel安装与部署

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

Message queue data storage MySQL table design

四象限时间管理有多好用?

【CUDA学习笔记】初识CUDA

OAuth2:使用JWT令牌

Efficient use of RecyclerView Section 1

The paper manual becomes 3D animation in seconds, the latest research of Wu Jiajun of Stanford University, selected for ECCV 2022
随机推荐
OAuth2:搭建授权服务器
The meaning of node_exporter performance monitoring information collection in Prometheus
UnityShader入门学习(二)——渲染流水线
OpenShift 4 - 用 Operator 部署 Redis 集群
435. 无重叠区间
网线RJ45接口针脚[通俗易懂]
最小费用最大流问题详解
Ubantu专题4:xshell、xftp连接接虚拟机以及设置xshell复制粘贴快捷键
svn安装及使用(身体功能手册)
Getting started with UnityShader (3) - Unity's Shader
Jmeter常用的十大组件
MANIFEST.MF文件(PDB文件)
R语言向前或者向后移动时间序列数据(自定义滞后或者超前的期数):使用dplyr包中的lag函数将时间序列数据向前移动一天(设置参数n为正值)
The use of thread pool two
The 232-layer 3D flash memory chip is here: the single-chip capacity is 2TB, and the transmission speed is increased by 50%
abaqus find contact pairs报错:surface name is already in use
RecyclerView高效使用第二节
Five dimensions to start MySQL optimization
Asynchronous processing business using CompletableFuture
SQL、HQL、JPQL 到底有什么区别