<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#container{
width: 100%; height: 200px; line-height: 200px; text-align: center; color: #fff; background-color: #444; font-size: 30px;
}
</style>
</head>
<body>
<div id="container">
<script>
/*
节流的概念:就是我们再当前这段时间里面只设置这个请求发送一次,必须是过了这个时间才能发送请求
*/
var count = 1;
var container = document.getElementById('container');
function getUserAction(e) {
console.log(e);
container.innerHTML = count++;
};
//时间戳的方式节流
//让我们来看第一种方法:使用时间戳,当触发事件的时候,我们取出当前的时间戳,然后减去之前的时间戳(最一开始值设为 0 ),如果大于设置的时间周期,就执行函数,然后更新时间戳为当前的时间戳,如果小于,就不执行。
//看了这个表述,是不是感觉已经可以写出代码了…… 让我们来写第一版的代码:
function dar(func, wait){
var kl,ol;
var shijian=0
return function(){
//首先获得当前时间的时间戳,然后让当前的时间戳减去第一次点击的时候的变量
//里面让当前的变量等于第一次点击的时间,然后再点击执行判断 此时,shijian就是上一次点击的时间
//gh-shijian就是上次到下一次点击的时间差,wait是我们输入的时间,然后判断是下次点击是否到时间了
var date=new Date()
var gh=date.getTime()
kl=this
ol=arguments
if(gh-shijian>wait){
func.apply(kl, ol);
shijian = gh;
}
}
}
//第二版用定时器
//当触发事件的时候,我们设置一个定时器,再触发事件的时候,如果定时器存在,就不执行,直到定时器执行,然后执行函数,清空定时器,这样就可以设置下个定时器。
function dfg(fun,wait){
var kl,ol
var timeout;//这个是设置的定时器 到时候会判断这个定时器存在不存在
return function(){
kl=this
ol=arguments//这个是为了打印这个函数的对象就是上面函数传入的e
if(!timeout){//代表这个定时器不存在
timeout=setTimeout(function(){
timeout=null//定时器执行完就清除了
fun.apply(kl,ol)
})
}
}
}
container.onmousemove =dar(getUserAction, 1000);
</script>
</body>
</html>