下划线反跳与原始Javascript setTimeout [英] Underscore debounce vs vanilla Javascript setTimeout

查看:90
本文介绍了下划线反跳与原始Javascript setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到Undercore.js中的debounce返回了一个将推迟执行直到等待时间结束的函数.

I understand that debounce in Undercore.js returns a function that will postpone its execution until the wait time is over.

我的问题是,使用debounce优于普通Javascript中的常规setTimeout函数是否有优势?他们俩工作不一样吗?

My question is, is there an advantage of using debounce over the regular setTimeout function in vanilla Javascript? Don't they both work the same?

推荐答案

它们非常不同,并且在完全不同的情况下使用.

They are very different and used in completely different cases.

  1. _.debounce返回一个functionsetTimeout返回一个id,可用于取消超时.

  1. _.debounce returns a function, setTimeout returns an id which you can use to cancel the timeOut.

无论您调用_.debounce返回的函数多少次,该函数在给定的时间范围内只会运行一次.

No matter how many times you call the function which is returned by _.debounce, it will run only once in the given time frame.

var log_once = _.debounce(log, 5000);

function log() {
  console.log('prints');
}

log_once();
log_once();
log_once();
log_once();
log_once();

var id = setTimeout(function() {
  console.log('hello');
}, 3000);
clearTimeout(id);

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

这篇关于下划线反跳与原始Javascript setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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