Friday, April 25, 2014

Lodash: Replacing setTimeout() With delay()

The built-in setTimeout() JavaScript function defers the the execution of a given function till a given number of milliseconds have passed. For the most part, this works perfectly — you pass in a function, and the duration to wait. Things aren't so straightforward when you already have a function defined, and you want to delay it's execution — especially when you want to invoke the function with specific parameters.

The first solution Lodash offers is keep using the setTimeout() function, but to wrap the function we're calling using partial(). For example, here's how we might do that.

function log( text ) {
    console.log( text );
}

setTimeout( _.partial( log, 'hello' ), 1000 );
setTimeout( _.partial( log, 'world' ), 1000 );

This solves a major headache for us, because there's no doubt that the correct parameters are being passed to the function, and we don't have to re-define an inline function, just for the purposes of setting a timeout. Building on this concept, we can simplify this code even further.

function log( text ) {
    console.log( text );
}

_.delay( log, 1000, 'hello' );
_.delay( log, 1000, 'world' );

This is doing essentially the same thing for us as the code above — binding the function argument to the function we want to call — it's just a little shorter and to the point, which is always a plus.