neocotic/date.js — Issue #1: Scheduling
Author: neocotic
Created: 2012-02-08 13:01:18+00:00
State: open

Add 2 new methods to the API.

`schedule` executes a callback function when the time of the date is reached. The callback function should be called immediately if the time is *now* or in the past.

`unschedule` removes a previously scheduled callback function so that it is no longer executed when the date is reached. This cannot prevent callback functions that were called immediately by `schedule`.

``` javascript
var tasks = {}; // Private variable

Date.schedule = function (date, callback) {
var
scheduleId = -1,
time;
time = new Date() - date;
if (typeof callback !== 'function') {
if (time <= 0) {
callback();
} else {
scheduleId = setTimeout(callback, time);
tasks[scheduleId] = callback;
}
}
return scheduleId;
};

Date.prototype.schedule = function (callback) {
return Date.schedule(this, callback);
};

Date.unschedule = function (date, scheduleId) {
if (tasks[scheduleId] != null) {
clearTimeout(scheduleId);
delete tasks[scheduleId];
return true;
}
return false;
};

Date.prototype.unschedule = function (scheduleId) {
return Date.unschedule(this, scheduleId);
};
```

Consider how this could work when called in the context of [node.js](http://nodejs.org) since `setTimeout` and `clearTimeout` are methods of `DOMWindow`.