<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
html,body {
height: 500%;
}
</style>
</head>
<body>
<button id="btn">按钮</button>
<script type="text/javascript">
// 什么是函数节流?什么是函数防抖?
/*
函数节流:一个函数执行一次后,只有大于设定的执行周期后才会执行第二次。
意思是一个需要频繁触发的函数,出于优化性能的角度,在规定的时间内,只让函数触发的第一次生效,后面不生效
*/
/**
* 节流函数
* @param fn 要节流的函数
* @param delay 规定的时间
*/
function throttle(fn,delay) {
// 记录上一次函数触发的时间
var lastTime = 0;
return function() {
// 记录当前函数触发的时间
var nowTime = Date.now();
if(nowTime-lastTime>delay){
// 修正this指向问题
fn.call(this);
// 同步时间
lastTime=nowTime;
}
}
}
// document.onscroll=throttle(function(){console.log('scroll事件被触发了' + Date.now())},200)
/*
防抖函数:一个需要频繁触发的函数,在规定时间内,只让最后一次生效,前面的不生效
*/
function debounce(fn,delay) {
// 记录上一次的延时器
var timer = null;
return function() {
// 清除上一次的延时器
clearTimeout(timer);
// 重新设置新的延时器
timer = setTimeout(function() {
fn.apply(this);
},delay)
}
}
document.getElementById('btn').onclick = debounce(function() {console.log('点击事件被触发了' + Date.now())},1000)
</script>
</body>
</html>
05-14
341
