Skip to content

Instantly share code, notes, and snippets.

@cdata
Last active December 30, 2015 04:39
Show Gist options
  • Save cdata/7777702 to your computer and use it in GitHub Desktop.
Save cdata/7777702 to your computer and use it in GitHub Desktop.
A fun JavaScript exercise.

Timebinder

I need a utility function. Let's call the function timebinder. This timebinder function expects two arguments: the first is a callback function, and the second is a number that represents some amount of milliseconds. The return value of the timebinder function is another function.

The function returned by timebinder expects a single argument: a context. When I call the returned function and pass a context, there is no return value. Then, the original callback function that I passed to timebinder should be called at the number of milliseconds I specified in the future.

Here are some example usages (assume we are executing in the browser window context):

var callback = function() {
  console.log('Context: ' + this);
};

var timedTwenty = timebinder(callback, 20);
var timedTen = timebinder(callback, 10);
var timedZero = timebinder(callback, 0);

timedTwenty(this);
timedZero(function() {});
timedTen({});

Given a correct implementation of timebinder and the above usages, I should see the following messages (in order as shown) in my console after twenty milliseconds has passed:

Context: function () {}
Context: [object Object]
Context: [object Window]
@seanknox
Copy link

seanknox commented Dec 3, 2013

[previous answer removed] 😸

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment