js之防抖节流

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#container {
width: 100px;
height: 100px;
background: #00eeff;
text-align: center;
line-height: 100px;
}
</style>
</head>
<body>

减少不必要的计算,不浪费资源,在合适的时候进行计算。

<div id="container"></div>
<script type="text/javascript">
var count=1;
var container=document.getElementById('container');

function getUserAction(){

console.log(this);
container.innerHTML=count++;
}

//防止谋一时间频繁触发事件。
//container.onmousemove=debounce(getUserAction,1000,true);
//防抖 谋一时间段只能执行一次。
function debounce(func,wait){
console.log("debounce");
var timeout;
return function(){
var self=this;
clearTimeout(timeout);
if(flag){//开始边界 进去就执行
var callNow=!timeout; //第一次进来

timeout=setTimeout(function(){
timeout=null;
},wait);

if(callNow){
func.apply(self);
}

}else{
timeout=setTimeout(function(){
func.apply(self);
},wait);
}
}
}


container.onmousemove=debounce(getUserAction,1000);
//节流 每隔一个周期执行一次。
function throttle(func,wait){
var prexious=0;
return function(){
var self=this;
var now =+new Date();
if(now-prexious>wait){
func.apply(self);
prexious=now;
}
}
}

</script>
</body>

</html>

posted @ 2019-04-30 10:44  asqw-only  阅读(139)  评论(0)    收藏  举报