console
let num = 1
let box = document.querySelector('#app')
box.innerText = num
function userAction(e,b){
console.log(e)
console.log(b)
box.innerText = num++
}
let userActionFn = throttle(userAction,1000,true)
box.onmousemove = function(e){
userActionFn(e,'bbbbb')
}
function debounce(fn, wait,im) {
let timer = null
return function() {
if(timer) clearTimeout(timer)
if(im){
let callNow = !timer
timer = setTimeout(()=>{
timer = null
fn.apply(this,arguments)
},wait)
if(callNow) fn.apply(this,arguments)
}else {
timer = setTimeout(()=>{
fn.apply(this,arguments)
}, wait)
}
}
}
function throttle(fn,wait){
let timeout = null
let previous = 0,remain = 0;
let throttled = function(){
let now = new Date().getTime()
let remain = wait -(now-previous)
if(remain<=0){
if(timeout){
clearTimeout(timeout)
timeout = null
}out
previous = now
fn.apply(this,arguments)
}else if(!timeout) {
timeout = setTimeout(()=>{
fn.apply(this,arguments)
previous = new Date().getTime()
timeout = null
},remain)
}
}
return throttled
}
<div id="app">
</div>
html,
body {
height: 100%;
width: 100%;
}
#app {
height: 100%;
width: 100%;
background: #666;
color: #fff
}