当前位置:网站首页>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;
}
}
}
边栏推荐
猜你喜欢
随机推荐
二叉查找树的综合应用
流水线设计的方法和作用「建议收藏」
2022最新整理软件测试常见面试题附答案
STP生成树选举结果查看及验证
C language two-dimensional array is called with one-dimensional array
罕见的数学天才,靠“假结婚”才得到追求事业的机会
System io statistics
xtrabackup
Mysql OCP 26题
兔起鹘落全端涵盖,Go lang1.18入门精炼教程,由白丁入鸿儒,全平台(Sublime 4)Go lang开发环境搭建EP00
MySQL 免安装版的下载与配置教程
SQL试题
【LeetCode】老虎证券面试-括号嵌套且满足优先级
删除文件夹时,报错“错误ox80070091:目录不是空的”,该如何解决?
使用 Scrapy 框架对重复的 url 无法获取数据,dont_filter=True
自动化测试浏览器驱动下载版本对应关系
ImportError: DLL load failed with error code -1073741795
bihashSummary
STP生成树(端口状态+端口角色+收敛机制 )|||| STP优化技术( uplinkfast技术+Portfast技术+backbonefast技术 )详解
Go的Gin框架学习









