源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Javascript Throttle & Debounce应用介绍

  • 时间:2022-08-09 10:36 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Javascript Throttle & Debounce应用介绍
[b]Throttle[/b] 无视一定时间内所有的调用,适合在发生频度比较高的,处理比较重的时候使用。
[u]复制代码[/u] 代码如下:
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); }; };
[b]Debounce[/b] 一定间隔内没有调用时,才开始执行被调用方法。
[u]复制代码[/u] 代码如下:
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); }; };
[b]Test[/b]
[u]复制代码[/u] 代码如下:
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);
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部