Underscore.js/lodash如何延迟执行函数 [英] How to execute functions with delay, underscorejs/lodash

查看:319
本文介绍了Underscore.js/lodash如何延迟执行函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript函数,可将数字打印到屏幕上.此功能可以打印很多数字,但是我使用的屏幕早于 Alan Turing 它不能这么快地打印数字!

I have a JavaScript function that prints numbers to the screen. This function prints a lot of numbers, but I am using a screen as old as Alan Turing so it can't print the numbers so fast!

解决方案?使用 underscorejs

The solution? Throtlle/debounce/delay the prints using underscorejs or lodash.

我的第一个尝试是使用throttle.

My first tentative was to use throttle.

let fun = num => {
  console.log(num);
};

let throttleFun = _.throttle(fun, 1000);

for (let i = 0; i < 10; i++) {
  throttleFun(i);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

但是它不是以1000ms的间隔打印所有数字,而是仅每1000ms调用一次函数,这导致它实际上只执行两次.

But instead of printing all the numbers with a 1000ms of separation, it just calls the function every 1000ms, which causes it to only actually execute twice.

我的下一个尝试是使用debounce:

My next try, was to use debounce:

let fun = num => {
  console.log(num);
};

let debouncedFn = _.debounce(fun, 1000);

for (let i = 0; i < 10; i++) {
  debouncedFn(i);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

现在,去抖动并不会打印出间隔为1000ms的值,而是实际上延迟了我的函数的执行时间,因为该函数上一次执行的时间为1000ms,这导致它仅执行一次.

Now, again, instead of printing the values with 1000ms of separation, debounce actually delays the execution of my function since it last executed by 1000ms, which causes it to only execute once.

我前面提到的所有行为均已记录在案,下划线和lodash的行为均相同.

All the behaviors I previously mentioned are documented, and they are the same for both underscore and lodash.

我的问题是:

  • 使用以前的一个库(或另一个类似的库),是否可以使用相似的函数样式在控制台中打印函数接收的参数,它们之间的间隔为1000ms?
  • Using one of the previous libraries (or another similar one), is there a way to print the arguments the function receives in the console with 1000ms of separation between them, using a similar function style?

请注意,虽然在这种情况下参数是数字,但实际上它们可以是字符串,对象或其他任何东西,而没有任何关联.

Please note that while in this case the arguments happen to be numbers, in reality they can be strings, objects or any other thing without any co-relation whatsoever.

推荐答案

您可以使用本机setInterval函数来实现:

You can do it with the native setInterval function:

let fun = num => {
  console.log(num);
};

let max = 10, i = 0;

let timer = setInterval(() => {
  fun(i);
  i++;
  if (i === max) {
    clearInterval(timer);
  }
}, 1000);

如果要使用下划线/破折号,请执行以下操作:

If you want to use a underscore/lodash, you do do something like so:

let fun = num => {
  console.log(num);
};

for (let i = 0; i < 10; i++) {
    _.delay(fun, 1000 * (i + 1), i);
}

这篇关于Underscore.js/lodash如何延迟执行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆