当前位置:网站首页>函数防抖与函数节流
函数防抖与函数节流
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>
边栏推荐
- 速速脱单诀窍
- Detailed Explanation of Addresses Delivered by DHCP on Routing/Layer 3 Switches [Huawei eNSP]
- GBsae 8 c database using an error, how to do?
- 抬升市场投资情绪,若羽臣是否还需“自身硬”?
- 四大网络攻击常见手段及防护
- 如何从PG导入数据到kingbaseES
- [Punctuality Atom STM32 Serial] Chapter 2 STM32 Introduction Excerpted from [Punctual Atom] MiniPro STM32H750 Development Guide_V1.1
- 思想茶叶蛋 (Jul 31,2022)| 元宇宙(Metaverse)下了一枚什么样的蛋
- 并发编程之生产者和消费者问题
- ZbxTable 2.0 重磅发布!6大主要优化功能!
猜你喜欢
cannot import name ‘import_string‘ from ‘werkzeug‘【bug解决】
Layer 3 Switch/Router OSPF Configuration Details [Huawei eNSP Experiment]
Post-94 Byte P7 posted the salary slip: It's really good to make up for this...
【正点原子STM32连载】第二章 STM32简介 摘自【正点原子】MiniPro STM32H750 开发指南_V1.1
一道[CSCCTF 2019 Qual]FlaskLight的详解再遇SSTI
【Attention】Dual Attention(DANet) & Fully Attention(FLA)
csdn图片去水印 | 其他方法无效时的解决方案
他97年的,我既然卷不过他...
记录十条工作中便利的API小技巧
TiDB升级与案例分享(TiDB v4.0.1 → v5.4.1)
随机推荐
SQL后计算的利器
GBsae 8 c database using an error, how to do?
inject() can only be used inside setup() or functional components.
【高并发基石】多线程、守护线程、线程安全、线程同步、互斥锁
How to import data from PG to kingbaseES
ZbxTable 2.0 重磅发布!6大主要优化功能!
【Attention】Dual Attention(DANet) & Fully Attention(FLA)
Could you please talk about how the website is accessed?[Interview questions in the web field]
TiDB升级与案例分享(TiDB v4.0.1 → v5.4.1)
关于Oracle RAC 11g重建磁盘组的问题
Post-94 Byte P7 posted the salary slip: It's really good to make up for this...
从零开始的tensorflow小白使用指北
去掉js代码文件所有注释
Fiddler(一)安装
yuv420sp转jpg
软件工程国考总结——判断题
用OpenGL绘制winXP版扫雷的笑脸表情
华为od项目
请你谈谈网站是如何进行访问的?【web领域面试题】
将jpg图片转换成yuv420(NV12)数据文件