转自:https://github.com/mqyqingfeng/Blog
1,(防抖)在事件触发n秒后执行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="author" content="杨欣">
<title>防抖</title>
<style>
#container {
width: 100%;
height: 200px;
line-height: 200px;
text-align: center;
color: #fff;
background: #000;
font-size: 30px
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var count = 0;
var container = document.getElementById("container");
function getUserAction(e) {
console.log(e);
container.innerHTML = count++;
}
// container.onmousemove = getUserAction;
//在事件触发n秒后再执行(第一版)
// function debounce(func,wait){
// var timer;
// return function(){
// clearTimeout(timer);
// timer=setTimeout(func,wait);
// }
// }
container.onmousemove = debounce(getUserAction, 500);
//在事件触发n秒后再执行(第二版)
function debounce(func, wait) {
var timer;
return function () {
var context = this;
var args = arguments;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args)
}, wait);
}
}
</script>
</body>
</html>
2.(节流)每隔一段时间只执行一次事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="author" content="杨欣">
<title>节流</title>
<style>
#container {
width: 100%;
height: 200px;
line-height: 200px;
text-align: center;
color: #fff;
background: #000;
font-size: 30px
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var count = 0;
var container = document.getElementById("container");
function getUserAction(e) {
console.log(e);
container.innerHTML = count++
}
// container.onmousemove = getUserAction;
//节流原理:如果持续触发事件,则每隔一段时间只执行一次事件(使用时间戳或者定时器)
//1.使用时间戳
// function throttle(func, wait) {
// var context, args;
// var previous = 0;
// return function () {
// var now = +new Date();
// context=this;
// args=arguments;
// if(now-previous>wait){
// func.apply(context,args)
// previous=now;
// }
// }
// }
container.onmousemove = throttle(getUserAction, 1000)
//2.使用定时器 触发事件的时候,设置一个定时器,如果定时器存在,就不执行,直到定时器执行,然后执行函数,清空定时器,在设置下一个定时器
function throttle(func, wait) {
var context, args, timeout;
return function () {
if (!timeout) {
context = this;
args = arguments;
timeout = setTimeout(function () {
timeout = null;
func.apply(context, args)
}, wait)
}
}
}
function debounce(func, wait) {
var timer;
return function () {
var context = this;
var args = arguments;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args)
}, wait);
}
}
</script>
</body>
</html>