首先看一个没有经过任何处理的:
1 // 模拟一个输出的函数
2 function input(value) {
3 console.log(`输入的内容${value}`)
4 }
5 const ipt = document.getElementById('input')
6
7 ipt.addEventListener("keyup",function(e){
8 input(e.target.value)
9 })
效果如下:
可以发现,只要按下键盘就会触发函数调用,这样在某些情况下会造成资源的浪费,在这些情况下,可能只需要在输入完成后做请求,比如身份验证等。
首先看下效果:
由此可以看出来,当我们重新频繁的输入后,并不会立即调用方法,只有在经过指定的间隔内没有输入的情况下才会调用函数方法;
代码如下:
1 function input(value) {
2 console.log(`输入的内容${value}`)
3 }
4 const ipt = document.getElementById('input')
5
6 function debounce(fun,delay){
7 let timer ;
8 return function(args){
9 const that = this
10 clearTimeout(timer)
11 timer = setTimeout(function(){
12 fun.call(that,args)
13 },delay)
14 }
15 }
16 const debounceInput = debounce(input,500)
17 ipt.addEventListener("keyup",function(e){
18 debounceInput(e.target.value)
19 })
节流就是在规定的时间间隔呢,重复触发函数,只有一次是成功调用
先看下效果:
可以看到在一直输入的情况下每隔一段时间会触发一次函数
代码如下:
1 function input(value) {
2 console.log(`输入的内容${value}`)
3 }
4 const ipt = document.getElementById('input')
5
6 function throttle(fun,delay){
7 let last,timer;
8 return function(args){
9 const that = this
10 const now = +new Date()
11 if(last && now < last + delay){
12 clearTimeout(timer)
13 timer = setTimeout(function(){
14 fun.call(that,args)
15 },delay)
16 }else{
17 last = now
18 fun.call(that,args)
19 }
20 }
21 }
22 const throttleInput = throttle(input,1000)
23 ipt.addEventListener("keyup",function(e){
24 throttleInput(e.target.value)
25 })
手机扫一扫
移动阅读更方便
你可能感兴趣的文章