印象笔记原文链接:https://app.yinxiang.com/fx/183cb733-2e7b-4ea0-a3ad-d62345ae084f
一、什么是防抖和节流
二、区别和使用场景
三、代码实例 (注意打开控制台)
① 防抖
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>防抖</title>
</head>
<body>
防抖:<input type="text" id="content"/>
<script type="text/javascript">
var oContent = document.getElementById('content');
oContent.addEventListener('input', debounce(contentInput, 5000, true));
function contentInput() {
console.log('Typing . . . ')
}
function debounce(fn, time, triggleNow) {
var t = null,
res;
var debounced = function () {
var _self = this,
args = arguments;
if(t){
clearTimeout(t);
}
if(triggleNow){
var exec = !t;
t = setTimeout(function () {
t = null;
}, time);
if(exec){
res = fn.apply(_self, args);
}
} else {
t = setTimeout(function () {
res = fn.apply(_self, args);
}, time);
}
return res;
}
debounced.remove = function () {
clearTimeout(t);
t = null;
}
return debounced;
}
</script>
</body>
</html>
② 节流
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>节流</title>
</head>
<body>
节流:<input type="text" id="content"/>
<script type="text/javascript">
var oContent = document.getElementById('content');
oContent.addEventListener('input', throttle(contentInput, 1000));
function contentInput() {
console.log('Typing . . . ')
}
function throttle(fn, delay) {
var t = null,
begin = new Date().getTime();
return function () {
var _self = this,
args = arguments,
cur = new Date().getTime();
clearTimeout(t);
if(cur - begin >= delay){
fn.apply(_self, args);
begin = cur;
} else {
t = setTimeout(function () {
fn.apply(_self, args);
}, delay)
}
}
}
</script>
</body>
</html>