<!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">
<title>Js节流防抖</title>
<style>
#root{
width:200px;
height:200px;
background-color: #ccc;
}
</style>
</head>
<body>
<div id="root">
</div>
<script>
var root = document.querySelector('#root');
var content = 0;
var timeout;
var write = function(){
content++;
this.innerHTML = content;
}
var debounce = function(fn,wait,flag){
return function(){
var __self = this;
clearTimeout(timeout);
if(flag){
var callNow = !timeout;//通过timeout 的真假,控制函数 fn 执行
timeout = setTimeout(function(){
timeout = null;
},wait);
if(callNow){
fn.apply(__self);
}
}else{
timeout = setTimeout(function(){
fn.apply(__self);
},wait);
}
}
}
//开始边界 鼠标进去,立马加1
//结束边界 鼠标进去,1秒后加1
//root.onmousemove = debounce(write,600,true);
var throttle = function(fn,wait){
var pre = 0;
return function(){
var now = +new Date();
var self =this;
if(now - pre > wait){
fn.apply(self);
pre = now;
}
}
}
//root.onmousemove = debounce(write,600,true);//开源
root.onmousemove = throttle(write,600);//节流
</script>
</body>
</html>
欢迎关注:http://www.w3schools.top/ 学习您想要的一切IT教程!