<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>函数节流与防抖</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style type="text/css">
</style>
</head>
<body>
<input type="text">
<div id="panel" style="background:red;width:200px;height:200px"></div>
<script>
//函数防抖 是只有在函数有足够的空闲时间的时候 才会触发 节流是在一段时间内触发
function debounce(func, delay){
var timeout
return function(e){
console.log('清除', timeout, e.target.value)
clearTimeout(timeout)
var context = this, args = arguments
console.log("新的", timeout, e.target.value)
timeout = setTimeout(function(){
console.log('---')
console.log(context)
func.apply(context, args)
}, delay)
}
}
var validate = debounce(function(e){
console.log('change', e.target.value, new Date-0)
}, 380)
document.querySelector('input').addEventListener('input', validate)
console.log(12)
// 节流
//节流的概念可以想想一下水坝,你建了水坝在河道中,不能让水流动不了,你只能让水流慢些。
//你不能让用户的方法都不执行。如果这样干,就是debounce了。为了让用户的方法在某个时间段内只执行一次,我们需要保存上次执行的事件点与定时器
function throttle(fn, threshhold){
var timeout
var start = new Date
var threshhold = threshhold || 160
return function(){
var context = this, args = arguments, curr = new Date() - 0
clearTimeout(timeout) //总是干掉时间回调
if(curr - start >= threshhold){
console.log('now', curr, curr - start) //注意这里相减的结果,都差不多是160左右
fn.apply(context, args) //只执行一部分方法,这些方法是在某个时间段内执行一次
start = curr
}else{
//让方法在脱离事件后也能执行一次
timeout = setTimeout(function(){
fn.apply(context, args)
}, threshhold)
}
}
}
var mousemove = throttle(function(e){
console.log(e.pageX, e.pageY)
})
document.querySelector('#panel').addEventListener('mousemove', mousemove)
</script>
</body>
</html>
函数节流与防抖
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 对象的深浅拷贝 对象的深拷贝与浅拷贝的区别: 浅拷贝:仅仅复制对象的引用, 而不是对象本身。 深拷贝:把复制的对象...