下划线反跳与原始Javascript setTimeout [英] Underscore debounce vs vanilla 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.
-
_.debounce
返回一个function
,setTimeout
返回一个id
,可用于取消超时.
_.debounce
returns afunction
,setTimeout
returns anid
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屋!