js实现输入框防抖功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text">
<script>
let input = document.querySelector("input");
input.addEventListener('input', debounce(function (e,b) {
console.log(e);
}, 3000))
input.addEventListener('input', throttle(function (e, b) {
console.log(e);
}, 3000,true))
function throttle(fn, delay,once) {
let timer = null;
var once1=once
return function () {
let context = this;
let args = arguments;
if (!timer) {
console.log(once1);
if(once1){
console.log(once1,'---------');
fn.apply(context, args);
once1=false
}
timer = setTimeout(function () {
fn.apply(context, args);
timer = null;
}, delay);
}
}
}
function debounce(fn, await) {
//第一个参数是函数,第二个参数时等待的时间
let timeout = null;
var args1 = arguments;
var count=0;
//let _that=this
return function (...args) {
// console.log(...args1);
// console.log(this);//这里的this指向当前调用者对象也就是 input
// console.log(...args);//所有的打印都是为了看清到底是谁被当做参数传递进来了
//这个地方用课解构es6的新特性,因为不知道会传递几个参数
//因为第一次定时器为空所以不会进入,当第二次触发也就是用户在此输入的时候就不为空了
//就会进入判断然后再让定时器为空,直到用户最后一次输入清除以后timeout就有值了就会执行定时器里面的操作了
if (timeout) {
// console.log(this);//这里的this指向当前调用者对象也就是 input
//如果timeout有值就清除定时器让定时器从新计时
clearTimeout(timeout);
}else {
if(count===0){
fn.apply(this, args)
}
//这个else可有可无,看自己是否需要用户第一次输入的值去做一些操作
//这个地方是使用apply改变一下this指向后面的参数就是我们传递的函数
//
}
timeout = setTimeout(() => {
count=1
fn.apply(this, args)
}, await)
}
}
</script>
</body>
</html>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
2021-08-03 vue element form 封装