首页 > 应用开发 > IT综合 > 详解JS函数的防抖和节流
节流实质上是:如果你持续触发事件,每隔一段时间,只执行一次事件。
根据这个需求我们可以通过时间戳实现节流:
//第一个实现方式
function
throttle
(func, wait) {
var context, args;
var previous =
0;
return
function
() {
var now = +new Date();
context = this;
args = arguments;
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}}//另外补充一下获取时间戳的方式吧// new Date().getTime()// Date.parse(new Date())// +new Date()// Date.now()// 通过判断再次点击时间与上次点击时间的时间戳是否大于传入的时间,来判断函数是否被执行
另一种实现方式通过定时器,通过判断定时器的存在来决定函数是否被执行
// 第二种实现方式
function
throttle
(func, wait) {
var timeout;
var previous =
0;
return
function
() {
context = this;
args = arguments;
if (!timeout) {
timeout = setTimeout(
function
(){
timeout = null;
func.apply(context, args)
}, wait)
}
}}//
看上面两种实现方式的代码,比较可以发现:
怎么中和实现一下两种方式呢?
//
第三种方式function
throttle(func,
wait,
options)
{
var
timeout,
context,
args,
result;
var
previous
=
0
;
if
(!options)
options
=
{};
var
later
=
function()
{
previous
=
options.leading
===
false
?
0
:
new
Date().getTime();
timeout
=
null
;
func.apply(context,
args);
if
(!timeout)
context
=
args
=
null
;
};
var
throttled
=
function()
{
var
now
=
new
Date().getTime();
if
(!previous
&&
options.leading
===
false
)
previous
=
now;
var
remaining
=
wait
-
(now
-
previous);
context
=
this;
args
=
arguments;
if
(remaining
<=
0
||
remaining
>
wait)
{
if
(timeout)
{
clearTimeout(timeout);
timeout
=
null
;
}
previous
=
now;
func.apply(context,
args);
if
(!timeout)
context
=
args
=
null
;
}
else
if
(!timeout
&&
options.trailing
!==
false
)
{
timeout
=
setTimeout(later,
remaining);
}
};
return
throttled;}
//leading:
false 表示禁用第一次执行
//trailing:
false 表示禁用停止触发的回调
//那就是 leading:
false 和 trailing:
false 不能同时设置。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69923331/viewspace-2695733/ ,如需转载,请注明出处,否则将追究法律责任。