├── BSD_LICENSE.txt ├── README.md ├── timed.js └── timed.min.js /BSD_LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011, Jarvis Badgley (chipersoft@gmail.com) 2 | Arthur Klepchukov (arthur.klepchukov@gmail.com) 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright 10 | notice, this list of conditions and the following disclaimer in the 11 | documentation and/or other materials provided with the distribution. 12 | * Neither the name of the nor the 13 | names of its contributors may be used to endorse or promote products 14 | derived from this software without specific prior written permission. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #Timed 2 | 3 | Timed provides syntactic sugar around JavaScript's native 4 | `setTimeout` and `setInterval` functions. 5 | 6 | To execute some code in 5 minutes, instead of writing: 7 | 8 | ```js 9 | setTimeout(function() { ... }, 300000); // how many zeros is that? 10 | ``` 11 | 12 | or the slightly more readable: 13 | 14 | ```js 15 | setTimeout(function() { ... }, 5 * 60 * 1000); // 5... (multiplies in head) min 16 | ``` 17 | 18 | now you can just write: 19 | 20 | ```js 21 | Timed.after(5, "minutes", function() { ... }); 22 | ```` 23 | 24 | `setTimeout` becomes `Timed.after` and `setInterval` becomes `Timed.every`. 25 | 26 | .every() and .after() both return a timer object which contains the calculated interval, a reference to the callback, the setTimeout/setInterval handle, and two control functions: 27 | 28 | - `timer.cancel()`: Cancels the timer and nulls timeout id. 29 | - `timer.start()`: Restarts the timer after it has been canceled, using the same callback as before. 30 | 31 | These two functions both return `this` to allow for chaining. 32 | 33 | ###.yield() 34 | 35 | Timed also provides a simple function yield processing time to the browser before executing the next block of code. 36 | 37 | ```js 38 | Timed.yield(function() { ... }); 39 | ``` 40 | 41 | This takes advantage of the `window.postMessage()` feature (when available) to execute the block as soon as the browser hands control back to JavaScript, often yielding faster results than a setTimeout can. In older browsers, .yield() falls back to a 0 millisecond timeout. 42 | 43 | ##Usage 44 | 45 | These are all valid calls: 46 | 47 | ```js 48 | Timed.after(100, function() { ... }); // 100 milliseconds 49 | Timed.after("9.7", function() { ... }); // 9.7 milliseconds 50 | Timed.after("50sec", function() { ... }); // 50 seconds 51 | Timed.after(7, "mins", function() { ... }); // 7 minutes 52 | Timed.after("33", "hours", function() { ... }); // 33 hours 53 | Timed.after("2 hours, 45 minutes", function() { ... }); // 2 hours, 45 minutes 54 | Timed.after("minute", function() { ... }); // 1 minute 55 | Timed.after([ 56 | ["1", "minute"], 57 | [34, "seconds"], 58 | "100 milliseconds" 59 | ], function() { ... }); 60 | ``` 61 | 62 | `Timed.every`, for creating intervals, has the same exact syntax as `$.after`. 63 | 64 | Valid time units include: 65 | 66 | * millisecond(s) (default) 67 | * ms 68 | 69 | * second(s) 70 | * sec(s) 71 | * s 72 | 73 | * minute(s) 74 | * min(s) 75 | * m 76 | 77 | * hour(s) 78 | * hr(s) 79 | * h 80 | 81 | * day(s) 82 | * d 83 | 84 | ##noConflict & jQuery 85 | 86 | Timed supports calling the `.noConflict()` function to remove the Timed namespace. `noConflict()` will then return the Timed object for assignment to a new location. 87 | 88 | If you wish to remap Timed's functions into jQuery's global object it can be done like so: 89 | 90 | ```js 91 | $.extend($, Timed.noConflict()); 92 | ``` 93 | 94 | 95 | ##Meta 96 | 97 | _Licensed under the 3-clause **BSD license** (BSD_LICENSE.txt)_ 98 | 99 | Copyright (c) 2011, Jarvis Badgley (chipersoft at gmail), Arthur Klepchukov (at gmail) 100 | -------------------------------------------------------------------------------- /timed.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Timed 3 | * Copyright (c) 2011 Jarvis Badgley, Arthur Klepchukov 4 | * https://github.com/ChiperSoft/Timed 5 | * Licensed under the BSD license (BSD_LICENSE.txt) 6 | * 7 | * @author Jarvis Badgley 8 | * @version 1.3.1 9 | */ 10 | 11 | 12 | (function (context) { 13 | 14 | var timer_cancel = function () { 15 | if (this.id && (1 || (this.type=='i')?clearInterval(this.id):clearTimeout(this.id))) this.id = null; 16 | return this; 17 | } 18 | 19 | var timer_start = function () { 20 | this.id = (this.type=='i')?setInterval(this.callback, this.when):setTimeout(this.callback, this.when); 21 | return this; 22 | } 23 | 24 | 25 | /** 26 | * Accepts more human-readable arguments for creating JavaScript timers and 27 | * converts them to values that can be inspected and passed along to 28 | * setTimeout or setInterval. 29 | * If the time when the timer should run is negative or faster than 30 | * the default it uses the default delay and default units. 31 | */ 32 | function create_timer() { 33 | var parsed = {when : null, callback : null, cancel : timer_cancel, start : timer_start}, 34 | ac = arguments.length; 35 | 36 | //parse callback function 37 | parsed.callback = arguments[ac - 1]; 38 | if (typeof parsed.callback !== 'function') throw ("Timed.after and Timed.every - Require a callback as the last argument"); 39 | 40 | //parse the first argument. if array, merge, otherwise force string. If a second argument is passed, append it as well. 41 | var period = (arguments[0] instanceof Array?arguments[0].join(''):String(arguments[0])) + (ac===3?String(arguments[1]):''); 42 | 43 | if (isNaN(parseInt(period,10))) period = '1'+period; 44 | 45 | var match = period.toLowerCase().replace(/[^a-z0-9\.]/g, "").match(/(?:(\d+(?:\.\d+)?)(?:days?|d))?(?:(\d+(?:\.\d+)?)(?:hours?|hrs?|h))?(?:(\d+(?:\.\d+)?)(?:minutes?|mins?|m\b))?(?:(\d+(?:\.\d+)?)(?:seconds?|secs?|s))?(?:(\d+(?:\.\d+)?)(?:milliseconds?|ms))?/); 46 | 47 | if (match[0]) { 48 | parsed.when = 49 | parseFloat(match[1]||0)*86400000 + //days 50 | parseFloat(match[2]||0)*3600000 + //hours 51 | parseFloat(match[3]||0)*60000 + //minutes 52 | parseFloat(match[4]||0)*1000 + //seconds 53 | parseInt(match[5]||0,10); //milliseconds 54 | 55 | } else if (ac===3 || !(parsed.when = parseInt(arguments[0],10))) { 56 | throw ("Timed.after and Timed.every - Could not parse delay arguments, check your syntax"); 57 | } 58 | 59 | return parsed; 60 | } 61 | 62 | var Timed = { 63 | /** 64 | * Syntactic sugar for setTimeout. 65 | * setTimeout(function() { ... }, 300000); // becomes: 66 | * Timed.after(5, "minutes", function() { ... }); 67 | * 68 | * // other valid calls: 69 | * Timed.after(100, function() { ... }); // 100 milliseconds 70 | * Timed.after("9.7", function() { ... }); // 9.7 milliseconds 71 | * Timed.after("50sec", function() { ... }); // 50 seconds 72 | * Timed.after("33", "hours", function() { ... }); // 33 hours 73 | * 74 | * Valid time units include millisecond, second, minute, hour, & day 75 | * along with all their common abbreviations and pluralizations. 76 | */ 77 | after : function after() { 78 | var timer = create_timer.apply(this, arguments); 79 | timer.type = 't'; 80 | return timer.start(); 81 | }, 82 | 83 | /** 84 | * Syntactic sugar for setTimeout. 85 | * 86 | * setInterval(function() { ... }, 300000); // becomes: 87 | * Timed.every(5, "minutes", function() { ... }); 88 | * 89 | * Supports the same syntax and arguments as Timed.after 90 | */ 91 | every : function every() { 92 | var timer = create_timer.apply(this, arguments); 93 | timer.type = 'i'; 94 | return timer.start(); 95 | }, 96 | 97 | yield : function yield(callback) { 98 | if (!!window.postMessage && !!window.addEventListener) { 99 | //uses the postMessage feature when available. postMessage events fire before the timeout loop triggers 100 | var wrapper, id = Math.round(Math.random()*1000000); 101 | window.addEventListener('message', wrapper = function (event) { 102 | if (event.data === id) { 103 | window.removeEventListener('message', wrapper); 104 | callback(); 105 | } 106 | }); 107 | window.postMessage(id, '*'); 108 | } else { 109 | //setTimeout fallback for browsers that don't support postMessage. 110 | Timed.after(0,'ms', callback); 111 | } 112 | } 113 | }; 114 | 115 | var oldTimed = context.Timed; 116 | Timed.noConflict = function () { 117 | context.Timed = oldTimed; 118 | return this; 119 | }; 120 | context.Timed = Timed; 121 | 122 | })(this); -------------------------------------------------------------------------------- /timed.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Timed 3 | * Copyright (c) 2011 Jarvis Badgley, Arthur Klepchukov 4 | * https://github.com/ChiperSoft/Timed 5 | * Licensed under the BSD license (BSD_LICENSE.txt) 6 | * 7 | * @author Jarvis Badgley 8 | * @version 1.3.1 9 | */ 10 | (function(d){function f(){var a={when:null,callback:null,cancel:g,start:h},c=arguments.length;a.callback=arguments[c-1];if(typeof a.callback!=="function")throw"Timed.after and Timed.every - Require a callback as the last argument";var b=(arguments[0]instanceof Array?arguments[0].join(""):String(arguments[0]))+(c===3?String(arguments[1]):"");isNaN(parseInt(b,10))&&(b="1"+b);b=b.toLowerCase().replace(/[^a-z0-9\.]/g,"").match(/(?:(\d+(?:\.\d+)?)(?:days?|d))?(?:(\d+(?:\.\d+)?)(?:hours?|hrs?|h))?(?:(\d+(?:\.\d+)?)(?:minutes?|mins?|m))?(?:(\d+(?:\.\d+)?)(?:seconds?|secs?|s))?(?:(\d+(?:\.\d+)?)(?:milliseconds?|ms))?/); 11 | if(b[0])a.when=parseFloat(b[1]||0)*864E5+parseFloat(b[2]||0)*36E5+parseFloat(b[3]||0)*6E4+parseFloat(b[4]||0)*1E3+parseInt(b[5]||0,10);else if(c===3||!(a.when=parseInt(arguments[0],10)))throw"Timed.after and Timed.every - Could not parse delay arguments, check your syntax";return a}var g=function(){if(this.id&&clearInterval(this.id))this.id=null;return this},h=function(){this.id=this.type=="i"?setInterval(this.callback,this.when):setTimeout(this.callback,this.when);return this},e={after:function(){var a= 12 | f.apply(this,arguments);a.type="t";return a.start()},every:function(){var a=f.apply(this,arguments);a.type="i";return a.start()},yield:function(a){if(window.postMessage&&window.addEventListener){var c,b=Math.round(Math.random()*1E6);window.addEventListener("message",c=function(d){d.data===b&&(window.removeEventListener("message",c),a())});window.postMessage(b,"*")}else e.after(0,"ms",a)}},i=d.Timed;e.noConflict=function(){d.Timed=i;return this};d.Timed=e})(this); 13 | --------------------------------------------------------------------------------