Permalink
Browse files

.after() and .every() now return a timer reference instead of the set…

…Timeout and setInterval ids. This reference contains a cancel() and start() function for resetting timers.
  • Loading branch information...
Twipped committed Jun 5, 2011
1 parent 1f03cfe commit 124062b8645948136c5b5a1e91ae4a94a4b23cac
Showing with 34 additions and 10 deletions.
  1. +7 −0 README.md
  2. +18 −5 timed.js
  3. +9 −5 timed.min.js
View
@@ -24,6 +24,13 @@ now you can just write:
`setTimeout` becomes `Timed.after` and `setInterval` becomes `Timed.every`.
+Both functions return a timer object which contains the calculated interval, a reference to the callback, the setTimeout/setInterval handle, and two control functions:
+
+- `timer.cancel()`: Cancels the timer and nulls timeout id.
+- `timer.start()`: Restarts the timer after it has been canceled, using the same callback as before.
+
+Both functions return `this` to allow for chaining.
+
Usage
-----
View
@@ -5,11 +5,23 @@
* Licensed under the BSD license (BSD_LICENSE.txt)
*
* @author <a href="mailto:chipersoft@gmail.com">Jarvis Badgley</a>
- * @version 1.1.1
+ * @version 1.2
*/
(function (context) {
+
+ var timer_cancel = function () {
+ if (this.id && (1 || (this.type=='i')?clearInterval(this.id):clearTimeout(this.id))) this.id = null;
+ return this;
+ }
+
+ var timer_start = function () {
+ this.id = (this.type=='i')?setInterval(this.callback, this.when):setTimeout(this.callback, this.when);
+ return this;
+ }
+
+
/**
* Accepts more human-readable arguments for creating JavaScript timers and
* converts them to values that can be inspected and passed along to
@@ -18,7 +30,7 @@
* the default it uses the default delay and default units.
*/
function create_timer() {
- var parsed = {when : null, callback : null},
+ var parsed = {when : null, callback : null, cancel : timer_cancel, start : timer_start},
ac = arguments.length;
//parse callback function
@@ -47,7 +59,6 @@
return parsed;
}
-
var Timed = {
/**
* Syntactic sugar for setTimeout.
@@ -65,7 +76,8 @@
*/
after : function after() {
var timer = create_timer.apply(this, arguments);
- return setTimeout(timer.callback, timer.when);
+ timer.type = 't';
+ return timer.start();
},
/**
@@ -78,7 +90,8 @@
*/
every : function every() {
var timer = create_timer.apply(this, arguments);
- return setInterval(timer.callback, timer.when);
+ timer.type = 'i';
+ return timer.start();
}
};
View

Some generated files are not rendered by default. Learn more.

Oops, something went wrong.

0 comments on commit 124062b

Please sign in to comment.