前端开发中的输入框的防抖和节流
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
</head>
<body>
用户名: <input onblur="checkUsername" placeholder="请输入用户名" id="username" />
<script>
var timer;
var count = 0;
var $username = document.getElementById('username');
$username.addEventListener('input', function () {
console.log(++count);
clearTimeout(timer);
timer = setTimeout(function () {
console.log('发请求到后台,检查用户是否已注册');
}, 1000)
}, false)
</script>
</body>
用户名: <input placeholder="请输入用户名" id="username" />
<script>
var timer;
var count = 0;
var $username = document.getElementById('username');
$username.addEventListener('input', throttle(function () {
console.log(++count);
}), false)
function throttle(callback) {
let preTime = Date.now();
return function () {
let args = arguments;
let now = Date.now();
if (now - preTime >= 1000) {
callback(args);
preTime = now;
}
}
}
</script>