广州明生堂生物科技有限公司


Javascript Throttle & Debounce应用介绍

网络编程 Javascript Throttle & Debounce应用介绍 06-22
Throttle
无视一定时间内所有的调用,适合在发生频度比较高的,处理比较重的时候使用。

var throttle = function (func, threshold, alt) {
var last = Date.now();
threshold = threshold || 100;
return function () {
var now = Date.now();
if (now - last < threshold) {
if (alt) {
alt.apply(this, arguments);
}
return;
}
last = now;
func.apply(this, arguments);
};
};

Debounce
一定间隔内没有调用时,才开始执行被调用方法。

var debounce = function (func, threshold, execASAP) {
var timeout = null;
threshold = threshold || 100;
return function () {
var self = this;
var args = arguments;
var delayed = function () {
if (!execASAP) {
func.apply(self, args);
}
timeout = null;
};
if (timeout) {
clearTimeout(timeout);
} else if (execASAP) {
func.apply(self, args);
}
timeout = setTimeout(delayed, threshold);
};
};

Test

var test = function (wrapper, threshold) {
var log = function () {
console.log(Date.now() - start);
};
var wrapperedFunc = wrapper(log, threshold);
var start = Date.now();
var arr = [];
for (var i = 0; i < 10; i++) {
arr.push(wrapperedFunc);
}
while(i > 0) {
var random = Math.random() * 1000;
console.log('index: ' + i);
console.log('random: ' + random);
setTimeout(arr[--i], random);
}
};
test(debounce, 1000);
test(throttle, 1000);

Javascript算符的优先级介绍
JavaScript中的运算符优先级是一套规则。该规则在计算表达式时控制运算符执行的顺序。具有较高优先级的运算符先于较低优先级的运算符执行。例如,

js导航菜单(自写)简单大方
最近由于项目需要一个简单的多级下拉菜单菜单但是由于业务和样式上的要求,为了简洁,在网上找了很多导航菜单控件都不大适合,所以突发奇想自

运算符&&的三个不同层次
运算符可以从三个不同的层次进行理解。第一层理解当操作数都是布尔值时,&&对两个值执行布尔与(AND)操作。x==0&&y==0//只有当x和y都是0时,才返回true


编辑:广州明生堂生物科技有限公司

标签:运算符,优先级,都是,菜单,规则