Skip to content

Instantly share code, notes, and snippets.

@nshah57
Forked from cdata/timebinder.md
Created August 14, 2014 23:10
Show Gist options
  • Save nshah57/3d5340ed906cc6efe270 to your computer and use it in GitHub Desktop.
Save nshah57/3d5340ed906cc6efe270 to your computer and use it in GitHub Desktop.

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]

https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

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