博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaScript-性能优化,函数节流(throttle)与函数去抖(debounce)
阅读量:3660 次
发布时间:2019-05-21

本文共 1369 字,大约阅读时间需要 4 分钟。

我在写一个类似百度搜索框的自动提示功能时候,使用了AJAX+keydown事件。调试时候我发现,当在搜索框中输入文字的时候,控制台在不停发送AJAX。这在本地服务器测试还好,如果我把它拿到运行环境,很可能出现提示功能卡顿,甚至没等提示出现用户就输入完毕的现象。毕竟大家现在打字都很快啊。于是我找到了一个新技能,函数节流 & 函数去抖。

throttle 和 debounce 是解决请求和响应速度不匹配问题的两个方案。二者的差异在于选择不同的策略。

  • throttle 等时间间隔执行函数。
  • debounce 时间间隔 t 内若再次触发事件,则重新计时,直到停止时间大于或等于 t 才执行函数。

throttle

function throttle(fn, threshhold, scope) {
threshhold || (threshhold = 250); var last, timer; return function () {
var context = scope || this; var now = new Date(), args = arguments; if (last && now - last - threshhold < 0) { // hold on to it clearTimeout(timer); timer = setTimeout(function () {
last = now; fn.apply(context, args); }, threshhold); } else { last = now; fn.apply(context, args); } };}

调用方法

$('body').on('mousemove', throttle(function (event) {
console.log('tick');}, 1000));

debounce

function debounce(fn, delay) {
var timer = null; return function () {
var context = this, args = arguments; clearTimeout(timer); timer = setTimeout(function () {
fn.apply(context, args); }, delay); };}

调用方法

$('input.username').keypress(debounce(function (event) {
// do the Ajax request}, 250));

总结

这两个方法适用于会重复触发的一些事件,如:mousemove,keydown,keyup,keypress,scroll等。如果只绑定原生事件,不加以控制,会使得浏览器卡顿,用户体验差。为了提高js性能,建议在使用以上及类似事件的时候用函数节流或者函数去抖加以控制。

转载地址:http://vsefn.baihongyu.com/

你可能感兴趣的文章
Manthan, Codefest 19 (open for everyone, rated, Div. 1 + Div. 2) (异或+规律)
查看>>
Codeforces Round #635 (Div. 2) D. Xenia and Colorful Gems(二分)
查看>>
Codeforces Round #423 (Div. 1, rated, based on VK Cup Finals) B. High Load(树的直径+贪心)
查看>>
Codeforces Round #638 (Div. 2) D. Phoenix and Science(数学+思维)
查看>>
Codeforces Round #576 (Div. 1) C. Matching vs Independent Set(思维好题)
查看>>
Codeforces Round #639 (Div. 2) D. Monopole Magnets(bfs+模拟)(恶心的阅读理解题)
查看>>
一分钟搞懂与、或、非、异或优先级!
查看>>
CodeBlocks无法编译的解决方案
查看>>
关于ZigBee的学习笔记1.0
查看>>
秒懂!用通俗的话讲解“ZigBee终端节点入网”过程
查看>>
完美解决:Ubuntu 12.04右键没有打开终端选项
查看>>
快速理解:memmove和memcopy的区别
查看>>
strsep函数详解
查看>>
秒懂之atoi()函数!
查看>>
一分钟快速理解:模拟信号和数字信号!
查看>>
MQTT之QoS
查看>>
【JavaWeb开发】"web应用程序的根目录"与"web站点的根目录"的分析
查看>>
【JavaWeb开发】EL表达式和JSTL标签的使用
查看>>
Spring学习(6)-Spring Bean的生命周期
查看>>
Spring学习(8)-AOP之ProxyFactoryBean、RegexMethodPointcutAdvisor、BeanNameAutoProxyCreator
查看>>