当前位置:网站首页>函数防抖与函数节流
函数防抖与函数节流
2022-08-04 09:03:00 【来康二锅头】
什么是函数防抖?
频繁触发,但是只在特定的时间内才执行最后一次触发函数。
指的是,触发事件后在规定时间内只能执行一次,如果在规定时间内又触发了该事件,则会重新开始算规定时间
比如: 当你在电梯里面的时候,
电梯开始倒数5秒关闭门, 在5秒时间内,突然来了一个人, 门就会自动打开, 电梯就会重新计时5秒,如果在5秒时间内又又来了一个人,电梯就会又重新计时5秒。 开始倒计时 5 4 3 2 1,此时没有人来了,电梯关门开始运行。
function debounce(callback, time = 300) {
let i;
return function () {
clearTimeout(i);
i = setTimeout(callback, time);
}
}
绑定滚动条事件
window.onscroll = debounce(function () {
console.log("调用了一次");
}, 500);
具体应用
css:
<style>
*{
margin: 0;
padding: 0;
}
body{
height: 5000px;
background-color: aqua;
}
img{
position: fixed;
bottom: 100px;
right: 50px;
display: none;
}
</style>
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
< img id="returntop" src="./img/return.png" alt="">
</body>
</html>
js
<script>
//函数防抖
function delbounce(callback,time = 300){
let t;
return function(){
clearTimeout(t);
t = setTimeout(callback,time);
}
}
//绑定滚动条事件
window.onscroll = delbounce(returntop,200);
//onscroll 滚动条事件 属于window事件 不写到标签里
function returntop(){
//距离浏览器顶部的距离
console.log("调用了1次");
let num = document.body.scrollTop || document.documentElement.scrollTop;
// console.log(parseInt(num));
//判断隐藏和出现
if(parseInt(num) > 400){
document.getElementById("returntop").style = "display:block";
}else{
document.getElementById("returntop").style = "display:none";
}
}
</script>
二,节流:
限制一个函数在一定时间内只能执行一次。
为什么需要函数节流
前端开发过程中,有一些事件或者函数,会被频繁地触发(短时间按内多次触发)。
function throlle(callback,time){
let lasttime = new Date().getTime();
return function(){
let nowtime = new Date().getTime();
if (nowtime - lasttime > time){
lasttime = nowtime;
}
}
}
window.onscroll = throlle(function(){
console.log("调用了1次");
},500);
实际使用:
css
<style>
*{
margin: 0;
padding: 0;
}
body{
background: url(./img/login.gif) no-repeat;
background-size: 100%;
}
div.login{
width: 500px;
height: 360px;
background-color: rgba(0, 0, 0, 0.2);
border-radius: 10px;
margin: 50px auto;
}
div.login h1{
padding-top: 10px;
padding-bottom: 10px;
text-align: center;
color: white;
}
div.email,div.tel,div.pwd{
margin-left: 17px;
}
div.login div.email input,div.login div.tel input,div.login div.pwd input{
width: 450px;
height: 45px;
padding-left: 11px;
margin: 8px 0;
}
div.login div.btn button{
width: 450px;
height: 40px;
color: white;
background-color: rgba(0, 0, 0, 0.2);
border-radius: 20px;
text-align: center;
margin-top: 10px;
margin-left: 20px;
line-height: 40px;
border: 0;
}
div.login div.btn button:hover{
cursor: pointer;
background-color:rgba(0, 0, 0, 0.4) ;
}
div.login #emailarr,#telarr,#pwdarr{
color: red;
font-size: 12px;
}
</style>
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="login">
<h1>后台管理系统</h1>
<div class="email">
<input type="email" id="email" onblur="isEamil()" placeholder="请输入邮箱..." required><br>
<div id="emailarr"></div>
</div>
<div class="tel">
<input type="tel" pattern="^1([358][0-9]|4[456789]|66|7[0135678]|9[189])\d{8}$"
id="tel" onblur="isTel()" placeholder="请输入电话号码..." required><br>
<div id="telarr"></div>
</div>
<div class="pwd">
<input type="password" pattern="^[0-9a-zA-Z]{6,12}" onblur="isPwd()" id="pwd" placeholder="请输入密码..." required><br>
<div id="pwdarr"></div>
</div>
<div class="btn">
<button id="btn" disabled>登录</button>
</div>
</div>
</body>
</html>
js
<script>
//功能:表单验证
let emailState = false;
let telState = false;
let pwdState = false;
//验证邮箱格式是否正确
function isEamil(){
let email = document.getElementById("email");
if(email.validity.valueMissing){
email.style = "border:2px red solid";
document.getElementById("emailarr").innerHTML = "* 邮箱不能为空!";
emailState = false;
isState();
return false;
}
if(email.validity.typeMismatch){
email.style = "border:2px red solid";
document.getElementById("emailarr").innerHTML = "* 请输入正确的邮箱!";
emailState = false;
isState();
return false;
}
email.style = "border:2px green solid";
document.getElementById("emailarr").innerHTML = "";
emailState = true;
isState()
return true;
}
//验证电话号码格式是否正确
function isTel(){
let tel = document.getElementById("tel");
if(tel.validity.valueMissing){
email.style = "border:2px red solid";
document.getElementById("telarr").innerHTML = "* 电话号码不能为空!";
telState = false;
isState();
return false;
}
if(tel.validity.patternMismatch){
tel.style = "border:2px red solid";
document.getElementById("telarr").innerHTML = "* 请输入正确的电话号码!";
telState = false;
isState();
return false;
}
tel.style = "border:2px green solid";
document.getElementById("telarr").innerHTML = "";
telState = true;
isState()
return true;
}
//验证密码格式是否正确
function isPwd(){
let pwd = document.getElementById("pwd");
if(pwd.validity.valueMissing){
pwd.style = "border:2px red solid";
document.getElementById("pwdarr").innerHTML = "* 密码不能为空!";
pwdState = false;
isState();
return false;
}
if(pwd.validity.patternMismatch){
pwd.style = "border:2px red solid";
document.getElementById("pwdarr").innerHTML = "* 请输入正确的密码!";
pwdState = false;
isState();
return false;
}
pwd.style = "border:2px green solid";
document.getElementById("pwdarr").innerHTML = "";
pwdState = true;
isState()
return true;
}
//判断三个结果是否都为true removeAttribute() 删除获取的的某个节点的对应属性
function isState(){
if(emailState && telState && pwdState){
document.getElementById("btn").removeAttribute("disabled");
}else{
document.getElementById("btn").setAttribute("disabled","disabled");//设置属性
}
}
//登陆成功
function login(){
console.log("函数调用1次");
//将数据发给后台处理
//后台返回两种结果 error success
//将成功后的用户信息进行本地存储 userid token
// let userid = 123456;
// localStorage.setItem("userid",userid);
// location.href = "./logininfo.html";
}
document.getElementById("btn").onclick = throlle(login,5000);
function throlle(callback,time){
let lasttime = new Date().getTime();
return function(){
let nowtime = new Date().getTime();
if (nowtime - lasttime > time){//在time时间段 不能在调用函数
callback();
lasttime = nowtime;
}
}
}
</script>
边栏推荐
- cannot import name 'import_string' from 'werkzeug' [bug solution]
- Detailed explanation of NAT/NAPT address translation (internal and external network communication) technology [Huawei eNSP]
- Post-94 Byte P7 posted the salary slip: It's really good to make up for this...
- Could you please talk about how the website is accessed?[Interview questions in the web field]
- Wang Shuang's Assembly Language Chapter 4: The First Program
- 94后字节P7晒出工资单:狠补了这个,真不错...
- Fiddler(二)-手机抓包502错误解决方法
- [Cloud Residency Co-Creation] HCSD Celebrity Live Streaming – Employment Guide
- tcp连接的细节
- TiFlash 源码阅读(五) DeltaTree 存储引擎设计及实现分析 - Part 2
猜你喜欢
智汇华云 | 华云软件定义网络 DCI介绍
ShowMeAI —— Show u 三连
Implementation of redis distributed lock
leetcode二叉树系列(一)
【正点原子STM32连载】第一章 本书学习方法 摘自【正点原子】MiniPro STM32H750 开发指南_V1.1
PD 源码分析- Checker: region 健康卫士
三层交换机配置MSTP协议详解【华为eNSP实验】
[Cloud Residency Co-Creation] HCSD Celebrity Live Streaming – Employment Guide
ISO14443A读卡流程(作为示例参考)
94后字节P7晒出工资单:狠补了这个,真不错...
随机推荐
grafana手册之可视化配置图表table
leetcode经典例题——56.合并区间
【论文笔记】Understanding Long Programming Languages with Structure-Aware Sparse Attention
Convert callback function to Flow
Detailed explanation of switch link aggregation [Huawei eNSP]
How to restore the Youxuan database with only data files
yuv420sp转jpg
技术实现 | 图像检索及其在淘宝的应用
从零开始的tensorflow小白使用指北
加降息与BTC流动性事件策略研究
注意力机制
学会 Arthas,让你 3 年经验掌握 5 年功力
OAK-FFC-4P全网首次测试
MATLAB/Simulink快捷键
蜜芽CEO刘楠:垂直电商黄金时代已落幕 坚定转型品牌之路
Inheritance and the static keyword
Anton Paar安东帕密度计比重计维修DMA35性能参数
继承和static关键字
leetcode二叉树系列(一)
Shared_preload_libraries导致很多语法不支持