当前位置:网站首页>实现防抖与节流函数
实现防抖与节流函数
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('发起请求')
}
边栏推荐
- Word table to Excel
- AVH Deployment Practice (1) | Deploying the Flying Paddle Model on Arm Virtual Hardware
- The use of thread pool two
- Female service community product design
- Getting started with UnityShader (3) - Unity's Shader
- UnityShader入门学习(二)——渲染流水线
- 什么是消息队列呢?
- STM32(十)------- SPI通信
- OAuth2:搭建授权服务器
- Excel快速对齐表格的中姓名(两个字姓名和三个字姓名对齐)
猜你喜欢
随机推荐
TRACE32——C源码关联
SQL、HQL、JPQL 到底有什么区别
Efficient use of RecyclerView Section 2
DeepLab系列学习
ERROR: Failed building wheel for osgeo
Network cable RJ45 interface pins [easy to understand]
"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
c语言hello world代码(代码编程入门)
UnityShader入门学习(三)——Unity的Shader
女性服务社群产品设计
Introduction to BigDecimal, common methods
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
为什么毕业季不要表白?
易驱线主控芯片对比(电动三轮电机90O瓦世纪通达)
使用 PyTorch 检测眼部疾病
R language ggplot2 visualization: use the ggboxplot function of the ggpubr package to visualize the box plot, use the font function to customize the font size, color, style (bold, italic) of the legen
R语言向前或者向后移动时间序列数据(自定义滞后或者超前的期数):使用dplyr包中的lag函数将时间序列数据向前移动一天(设置参数n为正值)
sentinel与nacos持久化
2021 OWASP TOP 10 漏洞指南
乡村基冲刺港交所:5个月期内亏2224万 SIG与红杉中国是股东