Why does Underscore.js have a delay function?

Aadit M Shah picture Aadit M Shah · Jun 3, 2013 · Viewed 12.9k times · Source

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?

Answer

alex picture alex · Jun 3, 2013

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.