Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Underscore.js have a delay function?

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?

like image 520
Aadit M Shah Avatar asked Jun 03 '13 04:06

Aadit M Shah


2 Answers

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.

like image 172
alex Avatar answered Sep 28 '22 01:09

alex


Why does Underscore.js have a delay function?

Because dumb. This particular underscore.js method seems pretty stupid.

Cons

  1. additional function in lib means larger code base
  2. larger code base means more to maintain and more possible bugs
  3. code that uses this function now has a dependency on that lib
  4. lesser/nil improvement over native API means low cost:gain ratio
  5. new apis to learn

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 !

like image 34
Mulan Avatar answered Sep 28 '22 02:09

Mulan