js 节流函数 throttle
/*
callback:callback functionname
interval: millisecond */ function debounce(callback, interval) {
let debounceTimeoutId; return function(...args) {
clearTimeout(debounceTimeoutId);
debounceTimeoutId = setTimeout(() => callback.apply(this, args), interval);
};
} function throttle(callback, interval) {
let enableCall = true; return function(...args) {
if (!enableCall) return; enableCall = false;
callback.apply(this, args);
setTimeout(() => enableCall = true, interval);
}
}
/*
* 频率控制 返回函数连续调用时,fn 执行频率限定为每多少时间执行一次
* @param fn {function} 需要调用的函数
* @param delay {number} 延迟时间,单位毫秒
* @param immediate {bool} 给 immediate参数传递false 绑定的函数先执行,而不是delay后后执行。
* @param debounce {bool} 给 immediate参数传递false 绑定的函数先执行,而不是delay后后执行。debounce
* @return {function}实际调用函数
*/ var throttle = function(fn, delay, immediate, debounce) {
var curr = +new Date(),//当前时间
last_call = 0,
last_exec = 0,
timer = null,
diff, //时间差
context,//上下文
args,
exec = function () {
last_exec = curr;
fn.apply(context, args);
};
return function () {
curr = +new Date();
context = this,
args = arguments,
diff = curr - (debounce ? last_call : last_exec) - delay;
clearTimeout(timer);
if (debounce) {
if (immediate) {
timer = setTimeout(exec, delay);
} else if (diff >= 0) {
exec();
}
} else {
if (diff >= 0) {
exec();
} else if (immediate) {
timer = setTimeout(exec, -diff);
}
}
last_call = curr;
}
};
var setval = function(){
var mydate = new Date();
var s = mydate.getSeconds();
var ms = mydate.getMilliseconds();
document.getElementById("ipt").value=s+":"+ms; } //以下两种绑定方法都可以,特别是jquery绑定时.注意 $("#btn")[0]
//document.getElementById("btn").onclick = throttle(function(){ setval(); },1000,true,false);
$("#btn")[0].onclick = throttle(function(){ setval(); },1000,true,false);
以下转自:https://programmingwithmosh.com/javascript/javascript-throttle-and-debounce-patterns/
JavaScript patterns: Throttle and Debounce
Do you need to handle a specific event, but you want to control how many times your handler will be called in a given period of time? This is a very common problem and often happens when listening to events such as scroll, mousemove or resize, which are triggered dozens of times a second. But sometimes it’s desirable even for less “frenetic” events, like, for example, to limit an action that occurs when a certain button is clicked. In this article, we’ll cover two patterns to control the repeated call of event handlers: throttle and debounce.
The example app
In order to understand both patterns, we will use a simple example application that shows the current mouse coordinates in the screen and how many times these coordinates were updated. By looking at this counter, you will find it easier to compare how these two techniques can control the calling of an event handler. This is our app without any event control technique applied:
render(); document.body.addEventListener('mousemove', logMousePosition); let callsCount = 0;
const positionsEl = document.querySelector('.app__positions');
function logMousePosition(e) {
callsCount++;
positionsEl.innerHTML = `
X: ${e.clientX},
Y: ${e.clientY},
calls: ${callsCount}
`;
} function render() {
document.querySelector('#app').innerHTML = `
<h1 class="app__title">Mouse position (Without event control) </h1>
<div class="app__positions"></div>
`;
}
And here is how this initial version of our app behaves:
Did you notice the calls count? In just 7 seconds, the logMousePosition function was called 320 times! Sometimes you don’t want a given event handler to be called so many times in a period of time so short. Now, let’s see how to solve this issue.
Throttle
The throttle pattern limits the maximum number of times a given event handler can be called over time. It lets the handler be called periodically, at specified intervals, ignoring every call that occurs before this wait period is over. This technique is commonly used to control scrolling, resizing and mouse-related events.
We need to adapt the example app to use the throttle pattern. In order to do so, let’s change the addEventListener call of the original code to include the throttling logic:
let enableCall = true;
document.body.addEventListener('mousemove', e => {
if (!enableCall) return; enableCall = false;
logMousePosition(e);
setTimeout(() => enableCall = true, 300);
});
In the above code:
- We’re declaring a enableCall variable to control if the throttling interval is already over. This flag is initially set to true, in order to allow the handler to be called the first time.
- Every time a mousemove event is triggered, we test if the enableCall variable is true. If not, that means that the minimum wait period is not over yet and we won’t call the event handler that time.
- However, if the enableCall variable is true, we can execute the event handler normally. However, before doing so, we need to set our control flag to false in order to prevent the handler to be called again during the wait interval.
- After calling the event handler, we use the setTimeout function to set our flag back to true after 300 milliseconds. This way, our handler will only be authorized to run again when this minimum interval is over.
Now, let’s see how the app behaves after applying this technique:
The throttling logic works perfectly! Now, there’s a minimum interval of 300 milliseconds between the updates, drastically reducing our calls count.
A reusable throttle function
In order to make this code reusable, let’s extract it to a separate function:
document.body.addEventListener('mousemove', throttle(logMousePosition, 300)); function throttle(callback, interval) {
let enableCall = true; return function(...args) {
if (!enableCall) return; enableCall = false;
callback.apply(this, args);
setTimeout(() => enableCall = true, interval);
}
}
The logic here is the same as above. When called, the throttle function returns a new event listener. In this version, we’re using a common function in order to preserve the original this context and apply it to the passed callback.
Debounce
The debounce pattern allows you to control events being triggered successively and, if the interval between two sequential occurrences is less than a certain amount of time (e.g. one second), it completely ignores the first one. This process is repeated until it finds a pause greater than or equal to the desired minimum interval. Once it happens, only the last occurrence of the event before the pause will be considered, ignoring all the previous ones. A common use case for this pattern is to limit requests in a search box component that suggests topics while the user is typing.
Let’s adapt our example app to use the debounce pattern:
let debounceTimeoutId;
document.body.addEventListener('mousemove', (e) => {
clearTimeout(debounceTimeoutId);
debounceTimeoutId = setTimeout(() => logMousePosition(e), 300);
});
The above piece of code contains the essence of the debounce pattern. Every time the event we want to control is fired, we schedule a call to the handler for 300 milliseconds later (by using setTimeout) and cancel the previous scheduling (with clearTimeout). This way, we’re constantly delaying the execution of the handler function until the interval between two sequential events is equal to or greater than a given threshold time.
To sum up:
Let’s say we have a given event being triggered two times (A and B) and there’s an X interval between these two occurrences. If we want to control this event by applying a debounce of Y milliseconds, here’s how it will work:
- If X < Y, the A call will be ignored.
- If X >= Y, the B call is considered.
- In both cases, if the new interval after B is greater than or equal to Y, B will be considered too.
Now, let’s see how it behaves in practice:
A reusable debounce function
Finally, we can extract the pattern logic to a reusable function. This way, we can easily apply it in similar situations in the future:
document.body.addEventListener('mousemove', debounce(logMousePosition, 300));
function debounce(callback, interval) {
let debounceTimeoutId; return function(...args) {
clearTimeout(debounceTimeoutId);
debounceTimeoutId = setTimeout(() => callback.apply(this, args), interval);
};
}
Conclusion
- The debounce pattern delays the calling of the event handler until a pause happens. This technique is commonly used in search boxes with a suggest drop-down list. By applying this pattern, we can prevent unnecessary requests to the backend while the user is typing.
- The throttle pattern is more suitable for events that are triggered many times in a short period of time. This technique is normally used to control scrolling, resizing and mouse-related events. By using throttle, we can filter repeated executions of an event handler, enforcing a minimum wait time between calls.
If you really want to master the fundamentals of JavaScript, you need to check out Mosh’s JavaScript course. It’s the best JavaScript course out there! And if you liked this article, share it with others as well!
js 节流函数 throttle的更多相关文章
- 关于js节流函数throttle和防抖动debounce
废话不多说,直奔主题. 什么是throttle和debounce? 这两个方法的主要目的多是用于性能优化.最常见的应用尝尽就是在通过监听resize.scroll.mouseover等事件时候的性能消 ...
- js节流函数和js防止重复提交的N种方法
应用情景 经典使用情景:js的一些事件,比如:onresize.scroll.mousemove.mousehover等: 还比如:手抖.手误.服务器没有响应之前的重复点击: 这些都是没有意义的,重复 ...
- js节流函数高级版
节流函数其主要作用就是防止用户在短时间内多次触发该事件. <!DOCTYPE html> <html lang="en"> <head> < ...
- 简单的节流函数throttle
在实际项目中,总会遇到一些函数频繁调用的情况,比如window.resize,mouseover,上传进度类似的触发频率比较高的函数,造成很大的性能损耗,这里可以使用节流函数来进行性能优化,主要是限制 ...
- JavaScript 节流函数 Throttle 详解
在浏览器 DOM 事件里面,有一些事件会随着用户的操作不间断触发.比如:重新调整浏览器窗口大小(resize),浏览器页面滚动(scroll),鼠标移动(mousemove).也就是说用户在触发这些浏 ...
- Javascript中 节流函数 throttle 与 防抖函数 debounce
问题的引出 在一些场景往往由于事件频繁被触发,因而频繁地进行DOM操作.资源加载,导致UI停顿甚至浏览器崩溃. 在这样的情况下,我们实际上的需求大多为停止改变大小n毫秒后执行后续处理:而其他事件大多的 ...
- js实现防抖函数和节流函数
防抖函数(debounce) 含义:防抖函数指的是在特定的时间内没有再次触发,才得以进行接下来的函数运行: 用途:当window.onresize不断的调整大小的时候,为了避免不断的重排与重绘,可以用 ...
- vue实现输入框的模糊查询(节流函数的应用场景)
上一篇讲到了javascript的节流函数和防抖函数,那么我们在实际场合中该如何运用呢? 首先,我们来理解一下:节流函数首先是节流,就是节约流量.内存的损耗,旨在提升性能,在高频率频发的事件中才会用到 ...
- [概念] js的函数节流和throttle和debounce详解
js的函数节流和throttle和debounce详解:同样是实现了一个功能,可能有的效率高,有的效率低,这种现象在高耗能的执行过程中区分就比较明显.本章节一个比较常用的提高性能的方式,通常叫做&qu ...
随机推荐
- Daas
联想到这些年遇到的各种客户使用桌面虚拟化的场景,深有感触.桌面虚拟化技术并不一定适合所有的用户和场景,也不仅仅只是技术方面的问题.加强安全的方法有千万种,为何此客户情守桌面虚拟化呢?某客户已经规模化实 ...
- 【转】POP3、SMTP和IMAP之间的区别和联系
POP3 POP3是Post Office Protocol 3的简称,即邮局协议的第3个版本,它规定怎样将个人计算机连接到Internet的邮件服务器和下载电子邮件的电子协议.它是因特网电子邮件的第 ...
- Golang_test
package main import ( "fmt" "time" ) func GetName() { //没事玩一下循环 for i := 0; i &l ...
- python3图片裁剪+转换pdf+压缩
本地大量长图,要发送给别人,所以要对图片进行裁剪+转换pdf+压缩 import zipfile import os from concurrent.futures import ThreadPool ...
- Keepalived 双机web服务宕机检测切换系统软件
简介 Keepalived的作用是检测web服务器的状态,如果有一台web服务器死机,或工作出现故障,Keepalived将检测到,并将有故障的web服务器从系统中剔除,当web服务器工作正常后Kee ...
- SQL SERVER 生成建表脚本
/****** Object: StoredProcedure [dbo].[GET_TableScript_MSSQL] Script Date: 06/15/2012 11:59:00 ***** ...
- JavaScript判断字符串能否转化为数字
判断一个字符串能否转化为数字 我们常常使用parseInt函数. 不过该函数的适用范围是很小的. 一般说来对于 如下类似 var myStr = "123hello"; 使用par ...
- 如何创建自己的docker image并上传到DockerHub上
这里,记录一下比较常用的docker操作细节,对于初次使用者,可能有很大的帮助. docker作为云计算Paas层面的东西,风靡全世界了,主要是因为它小巧,好用,功能强大.今天主要介绍一下如何依据自己 ...
- CSS3中样式顺序
.box{ /*1*/ background: yellow; /*2*/ background: radial-gradient(ellise, yellow, red); } 就以上样式1和2的顺 ...
- HTML5 CANVAS 高级
加载图片 获取图像有三种方式: a : createImageData(),没有效率,一个像素一个像素的绘制: b : var img= document.getElementById("i ...