码迷,mamicode.com
首页 > Web开发 > 详细

js防抖和节流

时间:2019-12-26 13:02:32      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:input   搜索   callback   间隔   har   oct   fun   this   window   

常见应用场景:

(1)window的 resize 和 scroll 事件;

        如:滚动到页面底部加载更多,稍微滚动一下就会触发n多次scroll事件,如果每次触发scroll事件的时候都去判断一次是否已经滚动到了页面底部,无疑会造成资源的浪费。此时若使用js节流,每隔一定的时间(如500ms)进行一次判断,间隔期间只能有一次触发判断,既节省了资源,也不会影响用户体验。

(2)文字输入时的 keyup 事件;

        如:输入搜索关键词的时候,进行自动完成或者自动联想。同理,这种情况下用户每敲击一次键盘就会触发一次keyup事件,此时用户可能连一个字都没有输入完成==,此时可以使用js防抖,在用户停止输入的一段时间后(如500ms)触发判断,进行自动联想或者自动搜索;也可以使用js节流,每隔一段时间,进行一次判断的执行,既可以实现实时的自动联想,也不会出现过于频繁的请求。

(3)元素拖拽、移动时的 mousemove 事件;

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>防抖和节流demo</title>
</head>
<body>
<div class="container">
<label for="unDebounce">没有防抖的input</label>
<input type="text" id="unDebounce" />
<br>
<br>
<label for="debounce">防抖后的input</label>
<input type="text" id="debounce" />
<br>
<br>
<label for="throttle">节流后的input</label>
<input type="text" id="throttle" />
</div>
<script src="jquery-1.11.3.min.js"></script>
<script>
$(function () {
    function time() {
        let date = new Date();
       let h = date.getHours();
       let m = date.getMinutes();
       let s = date.getSeconds();
       h = h >= 10 ? h : ‘0‘ + h;
       m = m >= 10 ? m : ‘0‘ + m;
       s = s >= 10 ? s : ‘0‘ + s;
       return h + ‘:‘ + m + ‘:‘ + s;
}
// 模拟ajax请求
function ajax(value, time) {
console.log(‘ajax: ‘ + value + ‘; time: ‘ + time);
}
// 未防抖的输入框keyup事件
$("#unDebounce").on(‘keyup‘, function (e) {
ajax(e.target.value, time());
})
// 防抖后的input的keyup事件
//在事件被触发的n秒后执行回调,如果在这n秒内又被触发,则重新计时。
function debounce(callback, delay) {
let timerId = null;
return function (args) {
let that = this;
clearTimeout(timerId);
timerId = setTimeout(function () {
callback.call(that, args, time());
}, delay);
}
}
let debounceAjax = debounce(ajax, 500);
$("#debounce").on(‘keyup‘, function (e) {
debounceAjax(e.target.value);
})
//js节流
//规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。
function throttle(callback, delay) {
let last, deferId;
return function (args) {
let that = this;
// let now = new Date().getTime();
let now = +new Date();
if (last && now < last + delay) {
clearTimeout(deferId);
deferId = setTimeout(function () {
last = now;
callback.call(that, args, time());
}, delay);
} else {
last = now;
callback.call(that, args, time());
}
}
}
 
let throttleAjax = throttle(ajax, 1000);
$("#throttle").on(‘keyup‘, function (e) {
throttleAjax(e.target.value);
})
})
</script>
 
</body>
</html>

js防抖和节流

标签:input   搜索   callback   间隔   har   oct   fun   this   window   

原文地址:https://www.cnblogs.com/benmumu/p/12101225.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!