gpt4 book ai didi

javascript - 创建自己的 throttle 函数并使用 setTimeout 进行测试

转载 作者:行者123 更新时间:2023-11-30 16:28:44 26 4
gpt4 key购买 nike

我有一项任务是编写自己的 throttle 函数。它需要使用 setTimeout 通过一定数量的测试。

这是我的代码:

var throttle = function(func, delay) {
var counter = 0;
var calledOnce = false;
setInterval(function(){
counter++;
}, 1);
return function() {
if (counter > delay || !calledOnce) {
calledOnce = true;
counter = 0;
return func.apply(this, arguments);
}
};
};

我正在使用以下内容对其进行测试:

var callBack = function () {
console.log('called');
};

var func = throttle(callback, 1000);

func(); // should be called
setTimeout(func, 500); // should not be called
setTimeout(func, 1000); // should be called
setTimeout(func, 1500); // should not be called
setTimeout(func, 1900); // should not be called

但是,当我按照此处的方式运行我的代码时,该函数仅被调用一次,使用原始 func() 调用,并且没有调用 setTimeout 内的任何函数。

我的代码或使用 setTimeout 进行的测试是否有任何明显的问题?

最佳答案

你的代码有什么问题:

    setTimeout 相比,
  1. setInterval 的计算量很大。
  2. 您的测试在单线程上运行,部署代码时会是这样吗? - 不,我想不是。您可以记录调用函数的确切时间以及调用线程的时间。
  3. 当您有高负载或多个线程检查它们是否应该执行时,我认为您会遇到时间膨胀

仅仅因为您将它设置为以 1 毫秒的间隔运行并不意味着该浏览器会这样做。例如,如果我将它设置为 0 以强制它采用尽可能小的间隔并多次执行此操作以获得平均值,我发现我可以使用的最小间隔是 ~6 毫秒。在重负载的情况下,这会显着增加。

var start = new Date();
var i = 0, interval = setInterval(function(){
if (++i >= 1000) {
var end = new Date();
var result = (end-start)/1000;
$('#result').text("The average interval was "
+result+" milliseconds");
$('#browser').text(navigator.userAgent);
clearInterval(interval);
}
}, 0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<p id=result>Please wait about 10 to 20 seconds ...</p>
<p id=browser></p>

它是如何真正完成的

不算自己写的,算annotated underscore source throttle function :

Returns a function, that, when invoked, will only be triggered at most once during a given window of time. Normally, the throttled function will run as much as it can, without ever going more than once per wait duration; but if you’d like to disable the execution on the leading edge, pass {leading: false}. To disable execution on the trailing edge, ditto.

  _.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = _.now();
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;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};

来自 http://underscorejs.org/#throttle

throttle_.throttle(function, wait, [options]) 

Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.

By default, throttle will execute the function as soon as you call it for the first time, and, if you call it again any number of times during the wait period, as soon as that period is over. If you'd like to disable the leading-edge call, pass {leading: false}, and if you'd like to disable the execution on the trailing-edge, pass {trailing: false}.

var throttled = _.throttle(updatePosition, 100);
$(window).scroll(throttled);

关于javascript - 创建自己的 throttle 函数并使用 setTimeout 进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33687757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com