您的位置:首页 > 职场人生

每天一道前端面试题--throttle与debounce

2016-10-19 10:06 423 查看

今天我要和大家分享一下函数节流与函数去抖

案例—拖拽小球

这里我通过mousemove来移动canvas小球的案例来介绍函数节流与函数去

/*
---------------------------
转化坐标:这个方法很重要
---------------------------
@param point 鼠标的坐标

@return canvas画布上的坐标
*/
function pointToCanvas(point) {
var box = canvas.getBoundingClientRect();
return {
x: point.x - box.left,
y: point.y - box.top
}
}


/*
----------------------------
绘制圆的方法
----------------------------
*/
function draw() {
var e = arguments[0];
var point = pointToCanvas({x: e.clientX, y: e.clientY});
context.clearRect(0,0,canvas.width,canvas.height);
context.beginPath();
context.arc(point.x,point.y,20,0,Math.PI * 2, false);
context.stroke();
context.fill();
}


/*
---------------------
初学者一般会这样写
---------------------
*/
canvas.addEventListener('mousemove',function(e) {
draw(e);
},false);


因为mousemove触发的频率会很高,也会以为这你要花大量的时间去重绘,所以性能堪忧。LOL大家玩过吧,一般FPS60就可以玩这个游戏了,你也可以调到100或者200,那就要看你电脑的性能了,所以这里我们这个小球的移动也是可以调节它的FPS的,这里我们就要用到函数节流了。为了更好的理解函数节流和函数去抖,我研究了一下underscore.js v.1.8.3中的源码,很牛。

throttle–函数节流

通过underscore.js的学习,我实现了一个简单的throttle:

/*
函数节流 throttle
---------------------------------------------
减少函数不必要的执行次数。不会重置等待时间。
---------------------------------------------
@param func 需要节流的函数
@param wait 等待的时间

@return result
*/
function throttle(func, wait) {
var context, args, result;
//定时器ID
var timeId = null;
//延迟执行函数
var later = function() {
timeId = null;
result = func.apply(context, args);
context = args = null;
}
return function(){
var now = Date.now();
context = this;
args = arguments;
if(!timeId) {
timeId = setTimeout(later, wait);
}
return result;
}
}


实现小球移动的FPS60

canvas.addEventListener('mousemove',throttle(draw,1000 / 60),false);


debounce–函数去抖

通过underscore.js的学习,我实现了一个简单的debounce:

/*
函数去抖 debounce
----------------------------
一旦触发,便会重置等待时间
----------------------------
@param func 去抖的函数
@param wait 等待的间隔

@return result
*/
function debounce(func, wait) {
var context, args, result;
//定时器唯一标识
var timeId = null;

//延迟执行
var later = function() {
timeId = null;
result = func.apply(context, args);
context = args = null;
}

return function() {
context = this;
args = arguments;
if(!timeId) {
timeId = setTimeout(later, wait);
}
else {
//重置等待时间
clearTimeout(timeId);
timeId = setTimeout(later, wait);
}

return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息