当前位置:网站首页>js函数防抖和函数节流及其使用场景。
js函数防抖和函数节流及其使用场景。
2022-08-03 09:49:00 【笨笨鱼爱吃糖】
//防抖函数
function debounce(callback, time = 300) {
let i;
return function () {
clearTimeout(i);
i = setTimeout(callback, time);
}
}
//绑定滚动条事件
window.onscroll = debounce(function () {
console.log("调用了一次");
}, 500);
滚动条实际案例
<style>
* {
padding: 0;
margin: 0;
}
#returntop {
position: fixed;
bottom: 100px;
right: 30px;
display: none;
}
.con {
width: 100%;
height: 5000px;
background: gainsboro;
}
</style>
<body>
<div id="returntop">
<img src="/web/img/returntop.png">
</div>
<div class="con"></div>
</body>
<script>
function debounce(callback, time = 300) {
let t;
return function () {
clearTimeout(t);
t = setTimeout(callback, time);
}
}
window.onscroll = debounce(function () {
hide();
}, 500);
function hide() {
console.log("调用一次");
let num = document.body.scrollTop || document.documentElement.scrollTop;
if (parseInt(num) >= 400) {
document.getElementById("returntop").style = "display:block";
} else {
document.getElementById("returntop").style = "display:none";
}
}
// window.onscroll = function(){
// // console.log(document.body.scrollTop);
// // console.log(document.documentElement.scrollTop);
// let num = document.body.scrollTop || document.documentElement.scrollTop;
// 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 now = new Date().getTime();
if (now - lasttime > time) {
callback();
lasttime = now;
}
}
}
window.onscroll = throlle(function () {
console.log("调用了一次");
}, 1500);
登录时的实际案例
document.getElementById("login").onclick = throlle(login,5000);
function throlle(callback, time) {
let lasttime = new Date().getTime();
return function () {
let now = new Date().getTime();
if (now - lasttime > time) {
callback();
lasttime = now;
}
}
}
边栏推荐
- PostgreSQL的架构
- Mysql OCP 30题
- 【LeetCode】zj面试-把字符串转换成整数
- System io statistics
- Flink Yarn Per Job - 启动AM
- 015-平衡二叉树(一)
- 2022T电梯修理考试题及答案
- Promise 一: 基本问题
- go中select语句
- Rabbit and Falcon are all covered, Go lang1.18 introductory and refined tutorial, from Bai Ding to Hongru, the whole platform (Sublime 4) Go lang development environment to build EP00
猜你喜欢
随机推荐
2022T电梯修理考试题及答案
cass9.1快捷键怎么设置_cass9.1格式刷快捷键命令
浅聊缓存函数
MySQL——几种常见的嵌套查询
bihashSummary
cmd(命令行)操作或连接mysql数据库,以及创建数据库与表
按位取反怎么运算_按位取反运算
简述设计的意义是什么_定义和概念的最大区别
C language two-dimensional array is called with one-dimensional array
力扣递归训练
mongodb服务启动失败_mongodb启动不了
2022T电梯修理考试题及答案
系统io统计
015-平衡二叉树(一)
Index (3)
R语言ggplot2可视化数据点重合的散点图、数据点有重合、使用geom_smooth函数基于lm方法拟合数据点之间的趋势关系曲线、自定义数据点的大小、色彩、添加主标题、副标题、题注信息
STP和RSTP的BPDU报文中flag位 对比+分析
mysql数据库配置性能调优
Flink Yarn Per Job - 创建启动Dispatcher RM JobManager
Promise 二:关键问题









