<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>节流</title>
<style>
#wrapper {
width: 100%;
height: 200px;
line-height: 200px;
text-align: center;
color: #fff;
background-color: #444;
font-size: 30px;
}
</style>
</head>
<body>
<div id="wrapper"></div>
<script>
// 节流的原理很简单:如果你持续触发某个事件,特定的时间间隔内,只执行一次。
// 关于节流的实现,有两种主流的实现方式: 时间戳思路 定时器思路
// 这2种思路的区别: 第一种一开始就会执行,停止了也不会执行
// 第二种一开始不会执行,停止还会执行一次
var count = 1
var oDiv = document.getElementById('wrapper')
function getUserAction(){
oDiv.innerHTML = count ++
}
//时间戳思路:
// 1.当鼠标移入的时候,事件立刻执行
// 2.每过 5s 会执行一次,且移动10s会执行2次,意味着动作停止后不会再执行。
// function throttle(fn,wait){
// var timer
// var per =0
// var _this = this
// var arg = arguments
// return function(){
// var cur = Date.now()
// if(cur - per>wait) {
// fn(_this,arg)
// per = cur
// }
// }
// }
// oDiv.onmousemove = getUserAction
oDiv.onmousemove = throttle(getUserAction,1000)
//定时器思路
function throttle(fn,wait){
var timer
var _this = this
var arg = arguments
return function(){
if(timer) return
timer = setTimeout(function(){
fn.apply(_this,arg)
timer = null
},wait)
}
}
</script>
</body>
</html>