This is the source code for Underscore.js' delay
function:
_.delay = function (func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function () { return func.apply(null, args); }, wait);
};
How is this any different from setTimeout
? Why does Underscore.js need delay
?
It's a cross browser way of being able to pass extra arguments which will appear as the arguments to the callback, like setTimeout()
. This doesn't work in IE.
It can make your code prettier...
setTimeout(_.bind(function() { }, null, "arg1"), 1e3);
...vs...
_.delay(function() { }, 1e3, "arg1");
I agree that it's one of the less useful Underscore methods, which are outlined in Naomi's answer.
Why does Underscore.js have a delay function?
Because dumb. This particular underscore.js method seems pretty stupid.
Cons
Pros
this section intentionally left blank
I would just learn to use javascript and do something like
var hello = function() {
console.log("hello");
};
var delay = 1000;
window.setTimeout(hello, delay);
Simple, right? Underscore.js is sometimes pretty useless. Honestly, window.setTimeout
is perfectly useful just the way it is.
Here's another example to show how to pass an arg to the function
var Cat = function(name) {
function meow(message) {
console.log(name, "says meow!", message);
}
this.meow = meow;
};
var duchess = new Cat("Duchess");
window.setTimeout(duchess.meow.bind(duchess, "please feed me!"), 2000);
// 2 seconds later
// => Duchess says meow! please feed me!
If you can't depend on .bind
you can use a closure too
window.setTimeout(function() {
duchess.meow("please feed me!");
}, 1000);
Wow, that was difficult, though. I'm going back to underscore and lodash and jquery. This JavaScript stuff is tough !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With