├── .editorconfig ├── .gitignore ├── LICENSE.txt ├── README.md ├── examples ├── Ajax.js └── JSONP.js ├── js ├── README.md └── thread.js └── tests ├── AjaxInterrupt.html ├── AjaxKill.html ├── JoinAny.html ├── JoinWithDelayedError.html ├── JoinWithError.html ├── Parallel.html ├── Serial.html ├── SimpleReturn.html ├── TightLoop.html ├── YieldInterrupt.html └── lib ├── debug.js ├── flickr.js ├── spin.js └── spinner.js /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | [*] 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | indent_style = tab 11 | indent_size = 4 12 | 13 | [*.js] 14 | indent_style = space 15 | indent_size = 2 16 | 17 | [*.{diff,md}] 18 | trim_trailing_whitespace = false 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml 3 | *.svn -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | jsThreads 2 | ========= 3 | 4 | Cooperative "multithreading" in Javascript using generators. 5 | 6 | 7 | Motivation 8 | ---------- 9 | 10 | I want to avoid callback hell. Promises do a good job, but force you to manage 11 | namespace by including parameters to your then() functions. Threads have the 12 | benefit of (local) namespace pollution. 13 | 14 | Benefits 15 | -------- 16 | 17 | * **Multiple threads of control** - All the thrill of multi-threaded programming, with none of the race conditions, deadlocking, or corrupted state you have from real threading. 18 | * **Procedural style** - Functions can be written in familiar procedural style, instead of callback style. 19 | * **try/catch blocks work** - Because of he procedural style, throwing and catching exceptions continue to work as expected 20 | * **Threads are objects** - Thread objects allow you to monitor peer thread state and interrupt peer threads. 21 | 22 | 23 | Features 24 | -------- 25 | 26 | **Create a New Thread** 27 | 28 | Create a new thread of control, which is left to its own devices, and the caller can continue with its own work. 29 | 30 | Thread.run(function*(){ 31 | //DO WORK 32 | }); 33 | 34 | 35 | 36 | **Synchronous Calling Style** 37 | 38 | Thread.run(function*(){ 39 | var a = yield (requestDataFromServer()); 40 | //DO WORK 41 | var b = yield (anotherRequestToServer(a)); 42 | //MORE WORK 43 | var c = yield (yetAnotherRequest(b)); 44 | }); 45 | 46 | All function* calls are in order, as if written synchronously. The jsThread library will weave this function with others to achieve parallelism. 47 | 48 | 49 | **Wait for Thread to Complete** 50 | 51 | var t=Thread.run(function*(){...}); //MAKE THREAD 52 | yield (Thread.join(t)); //WAIT TO FINISH 53 | 54 | The ```join()``` function will return a structure (```{"threadResponse":value}```) 55 | with the last value handled by the joinee thread (`t`). This value is either the last 56 | yielded value or a thrown exception. 57 | 58 | Joining a thread will demand all child threads are joined too. 59 | 60 | **Sleep** 61 | 62 | yield (Thread.sleep(1000)); //JUST ONE SECOND 63 | 64 | ```sleep()``` can be interrupted with the ```kill()``` from another thread. 65 | 66 | **Cooperate** 67 | 68 | When performing long running operations on the main thread, it is a good idea to 69 | occasionally yield control to the other tasks and threads waiting to run. 70 | 71 | yield (Thread.yield()); //LET OTHER THREADS RUN 72 | 73 | A call to ```yield()``` may, or may not suspend, depending on the amount of time 74 | that has passed since the last ```suspend()``` 75 | 76 | The ```Thread.yield()``` call is a little slow: The call defers to the 77 | trampoline, which calls Thread.yield(), which returns a generator, which is then 78 | called by the trampoline, which returns the Thread.YIELD constant, which reminds 79 | the trampoline to check if it's time to yield to another task. It is more 80 | direct to simply provide the constant: 81 | 82 | yield (Thread.YIELD); //LET OTHER THREADS RUN (alternate) 83 | 84 | Admittedly, this breaks the standard ```yield (functionCall())``` form. 85 | 86 | **Stop Thread Early** 87 | 88 | var t=Thread.run(function*(){...}); //MAKE THREAD 89 | t.kill(); //KILL IT (Interrupt) 90 | 91 | Use this to ```abort()``` server requests or stop sleeping prematurely. The 92 | killed thread will then receive a ``Thread.Interrupt``` exception. 93 | This exception can be caught just like any other. It is important your code 94 | properly recognizes and handles this exception to shutdown cleanly. 95 | 96 | Killing a thread will also kill all children, which can include ajax requests 97 | and other scheduled processing. 98 | 99 | **Adding Children** 100 | 101 | myThread.addChild({"kill":function(){...}}) 102 | 103 | Child threads are added automatically to the ```Thread.currentThread``` when 104 | a thread is made. You are not limited to Threads: Any object that 105 | has a ```kill``` or ```abort``` function can be added. 106 | 107 | 108 | 109 | **Suspend/Resume Threads** 110 | 111 | You will inevitably require your threads interact with other callback-style 112 | Javascript libraries. To do this without busy waiting you need to *suspend* 113 | and *resume* your threads. [JSONP.js](./examples/JSONP.js) is an example of 114 | how to achieve this: 115 | 116 | var getJSON = function*(url) { 117 | //ASK FOR A CALLBACK THAT CAN RESUME THE CURRENT THREAD 118 | var callback = yield (Thread.Resume); 119 | 120 | //THIS CURRENT THREAD WILL RESUME WHEN callback IS CALLED 121 | var req = $.getJSON(url, callback); 122 | 123 | //SUSPEND UNTIL RESUME CALLBACK IS EXECUTED 124 | var json = yield (Thread.suspend(req)); 125 | 126 | //RETURN 127 | yield (json); 128 | };//function 129 | 130 | The idea is to ask the jsThreads system for a resume function: When called, 131 | this function will resume the current thread. In this case, the resume function 132 | is used as a callback and fed into a familiar JQuery call. Your final step is 133 | to suspend the thread and trust the resume function is eventually called. When 134 | the thread does resume, the first argument of the resume function (the callback) 135 | will be accessible as a yielded value. 136 | 137 | **AJAX** 138 | 139 | The AJAX callback style (with its success() and error() callbacks) is pervasive. 140 | Use the ```Thread.call()``` function to specifically provide these callbacks, 141 | yield the success() argument, and throw an exception if error() is called. 142 | [Ajax.js](.examples/Ajax.js) is a example of how to use it: 143 | 144 | var ajax = function*(param) { 145 | yield Thread.call($.ajax, param); 146 | };//function 147 | 148 | 149 | Drawbacks 150 | --------- 151 | 152 | Here are some of complications to look out for 153 | 154 | ####Only Works in Firefox (and Chrome with experimental javascript on)#### 155 | 156 | Generators have been around for a while, but other browsers (and js engines) have only 157 | started to implement them. To use generators in Chrome enable 158 | [experimental javascript](chrome://flags/#enable-javascript-harmony). 159 | 160 | ####Must be a Generator#### 161 | 162 | A common mistake is to forget the star (*) in the function definition. This will make 163 | it appear as if nothing happens 164 | 165 | - **BAD:** 166 | 167 | Thread.run(function(){ 168 | $("#message").html("Hi there"); 169 | }); 170 | 171 | 172 | - **GOOD:** 173 | 174 | Thread.run(function*(){ 175 | $("#message").html("Hi there"); 176 | }); 177 | 178 | ####Accidentally Calling Generators Directly#### 179 | 180 | With so many generators in your code, you may find yourself calling them like 181 | normal functions. This is bad. These 'normal' functions return generator objects, 182 | and do not fully execute on first call. If you find your function is not 183 | executing, this is probably the cause. 184 | 185 | - **BAD:** 186 | 187 | doSomeSetup(); //YOU CAN'T TELL, BUT THIS IS A 188 | //GENERATOR. IT WILL SEEM TO DO NOTHING 189 | 190 | - **GOOD:** 191 | 192 | yield (doSomeSetup()); //NOW IT WILL WORK 193 | 194 | This happens often to me when I am joining threads: 195 | 196 | - **BAD:** 197 | 198 | Thread.join(A); /HEY! Where are A's artifacts!? 199 | 200 | - **GOOD:** 201 | 202 | yield Thread.join(A); //Oh! I forgot to wait for A to finish. 203 | 204 | 205 | ####Hard to Debug#### 206 | 207 | Because ```Thread``` calls all generators directly, it can be impossible to see the 208 | stack trace you expect. 209 | 210 | Avoid this problem by keeping your threaded code from making deep threaded calls. 211 | If you need deep logic, it is better implemented with regular functions, called by 212 | the threaded code. 213 | 214 | ####Impossible States with Debugger#### 215 | 216 | When your debugger is on, AND you have your code paused, AND there are pending 217 | responses, all bets are off. The pending response will trigger the javascript 218 | engine to run despite the debugger, and mess with your program state. 219 | 220 | This is not a problem with jsThreads, it is a problem with debugging any 221 | javascript program; I just want you to be aware your program can be 222 | achieve *impossible* states when you are debugging. 223 | 224 | ####Can not us JS Functors#### 225 | 226 | You must pass a generator to ```Thread.run()```. Javascript's functor style can prevent 227 | elegant threaded code: 228 | 229 | - **BAD:** 230 | 231 | Thread.run(function*(){ 232 | $.each(array, function(item){ 233 | yield (callBackToServer()) //YIELD IS IN NESTED ANONYMOUS FUNCTION 234 | }); 235 | }); 236 | 237 | - **GOOD:** 238 | 239 | Thread.run(function*(){ 240 | for(var i=0;i

This page uses Javascript Generators!

' + 21 | '
I suggest using Firefox. If you must use Google Chrome, you can enable Experimental Javascript at chrome://flags/#enable-javascript-harmony (and then reboot).
' + 22 | 'If you must use IE, then I am sorry.
' + 23 | '' 24 | ); 25 | }, 26 | 5000 //A LITTLE DELAY WITH HOPE $ WILL BE DEFINED!! :) 27 | ); 28 | }//try 29 | 30 | 31 | var Thread; 32 | 33 | build = function(){ 34 | "use strict"; 35 | 36 | var currentTimestamp; 37 | if (Date.currentTimestamp) { 38 | currentTimestamp = Date.currentTimestamp; 39 | } else { 40 | currentTimestamp = Date.now; 41 | }//endif 42 | 43 | var DEBUG = false; 44 | var POPUP_ON_ERROR = true; 45 | var FIRST_BLOCK_TIME = 500; //TIME UNTIL YIELD 46 | var NEXT_BLOCK_TIME = 150; //THE MAXMIMUM TIME (ms) A PIECE OF CODE SHOULD HOG THE MAIN THREAD 47 | var YIELD = {"name": "yield"}; //BE COOPERATIVE, WILL PAUSE EVERY MAX_TIME_BLOCK MILLISECONDS 48 | 49 | //Suspend CLASS 50 | 51 | function suspend(request){ 52 | this.name = "suspend"; 53 | this.request = request; 54 | } 55 | 56 | var Suspend = suspend; 57 | 58 | var DUMMY_GENERATOR = { 59 | "close": function(){ 60 | } 61 | }; 62 | 63 | //RETURN FIRST NOT NULL, AND DEFINED VALUE 64 | function coalesce(){ 65 | var args = arguments; 66 | var a; 67 | for (var i = 0; i < args.length; i++) { 68 | a = args[i]; 69 | if (a !== undefined && a != null) return a; 70 | }//for 71 | return null; 72 | }//method 73 | 74 | Thread = function(gen){ 75 | if (typeof(gen) == "function") { 76 | try { 77 | gen = gen(); //MAYBE THE FUNCTION WILL CREATE A GENERATOR 78 | if (String(gen) !== '[object Generator]') { 79 | Log.error("You can not pass a function. Pass a generator! (have function use the yield keyword instead)"); 80 | }//endif 81 | } catch (e) { 82 | Log.error("Expecting a Generator!", e); 83 | }//endif 84 | }//endif 85 | 86 | this.keepRunning = true; 87 | this.gen = null; //CURRENT GENERATOR 88 | this.stack = [gen]; 89 | this.nextYield = currentTimestamp() + FIRST_BLOCK_TIME; 90 | this.children = []; 91 | }; 92 | 93 | Thread.YIELD = YIELD; 94 | 95 | 96 | //YOU SHOULD NOT NEED THESE UNLESS YOU ARE CONVERTING ASYNCH CALLS TO SYNCH CALLS 97 | //EVEN THEN, MAYBE YOU CAN USE Thread.call 98 | Thread.Resume = {"name": "resume"}; 99 | Thread.Interrupted = new Exception("Interrupted"); 100 | 101 | Thread.run = function(name, gen){ 102 | if (typeof(name) != "string") { 103 | gen = name; 104 | name = undefined; 105 | }//endif 106 | 107 | var output = new Thread(gen); 108 | output.name = name; 109 | output.start(); 110 | return output; 111 | };//method 112 | 113 | 114 | //JUST LIKE RUN, ONLY DOES NOT REGISTER THE THREAD IN isRunning 115 | Thread.daemon = function(name, gen){ 116 | if (typeof(name) != "string") { 117 | gen = name; 118 | name = undefined; 119 | }//endif 120 | 121 | 122 | Thread.currentThread.addChild(this); 123 | 124 | //START IN SILENT MODE 125 | var output = new Thread(gen); 126 | output.name = name; 127 | output.resume(output.stack.pop()); 128 | output.parentThread = Thread.currentThread; 129 | Thread.currentThread.addChild(this); 130 | return output; 131 | };//method 132 | 133 | 134 | //FEELING LUCKY? MAYBE THIS GENERATOR WILL NOT DELAY AND RETURN A VALID VALUE BEFORE IT YIELDS 135 | //YOU CAN HAVE IT BLOCK THE MAIN TREAD FOR time MILLISECONDS 136 | Thread.runSynchronously = function(gen, time){ 137 | if (String(gen) !== '[object Generator]') { 138 | Log.error("You can not pass a function. Pass a generator!"); 139 | }//endif 140 | 141 | var thread = new Thread(gen); 142 | if (time !== undefined) { 143 | thread.nextYield = currentTimestamp() + time; 144 | }//endif 145 | var result = thread.start(); 146 | if (result === Suspend) 147 | Log.error("Suspend was called while trying to synchronously run generator"); 148 | if (result instanceof Exception) { 149 | throw result; 150 | } else { 151 | return result; 152 | }//endif 153 | };//method 154 | 155 | 156 | Thread.getStackTrace = function(depth){ 157 | var trace; 158 | try { 159 | this.undef(); //deliberate error 160 | } catch (e) { 161 | trace = e.stack.replace(/(?:\n@:0)?\s+$/m, '').replace(/^[\(@]/gm, '{anonymous}()@').split('\n'); 162 | }//try 163 | return trace.slice(depth + 1); 164 | };//method 165 | 166 | 167 | //ADD A KILLABLE CHILD {"kill":function} 168 | function addChild(child){ 169 | this.children.push(child); 170 | child.parentThread = this; 171 | }//function 172 | Thread.prototype.addChild = addChild; 173 | 174 | var mainThread = {"name": "main thread", "children": [], "addChild": addChild}; 175 | Thread.currentThread = mainThread; 176 | Thread.isRunning = []; 177 | 178 | //REPLACE THESE WHEN YOU WANT SIGNALS ABOUT WORKING THREADS 179 | Thread.showWorking = function(){ 180 | }; 181 | Thread.hideWorking = function(){ 182 | }; 183 | 184 | 185 | Thread.prototype.start = function(){ 186 | Thread.isRunning.push(this); 187 | Thread.currentThread.addChild(this); 188 | Thread.showWorking(Thread.isRunning.length); 189 | return this.resume(this.stack.pop()); 190 | }; 191 | 192 | 193 | Thread.prototype.resume = function Thread_prototype_resume(retval){ 194 | Thread.showWorking(Thread.isRunning.length); 195 | while (this.keepRunning) { 196 | if (retval === YIELD) { 197 | if (this.nextYield < currentTimestamp()) { 198 | var self_ = this; 199 | setTimeout(function(){ 200 | self_.nextYield = currentTimestamp() + NEXT_BLOCK_TIME; 201 | self_.currentRequest = undefined; 202 | self_.resume(); 203 | }, 1 204 | ); 205 | return Suspend; 206 | } else { 207 | //simply resume 208 | }//endif 209 | } else if (String(retval) === '[object Generator]') { 210 | this.stack.push(retval); 211 | retval = undefined 212 | } else if (retval instanceof Suspend) { 213 | if (retval.request) { 214 | this.addChild(retval.request) 215 | }//endif 216 | if (!this.keepRunning) this.kill(new Exception("thread aborted")); 217 | if (this.stack.length == 0) 218 | Log.error("Should not happen"); 219 | return Suspend; 220 | } else if (retval === Thread.Resume) { 221 | (function(self){ 222 | retval = function(retval){ 223 | if (DEBUG) { 224 | Log.note("Resuming thread " + self.name) 225 | }//endif 226 | self.nextYield = currentTimestamp() + NEXT_BLOCK_TIME; 227 | self.currentRequest = undefined; 228 | self.resume(retval); 229 | }; 230 | })(this); 231 | } else { //RETURNING A VALUE/OBJECT/FUNCTION TO CALLER 232 | var expendedGenerator = this.stack.pop(); 233 | if (expendedGenerator.close !== undefined) 234 | expendedGenerator.close(); //ONLY HAPPENS WHEN EXCEPTION IN THREAD IS NOT CAUGHT 235 | 236 | if (this.stack.length == 0) { 237 | return this.shutdown(retval); 238 | }//endif 239 | }//endif 240 | 241 | var selfThread = Thread.currentThread; 242 | Thread.currentThread = this; 243 | try { 244 | this.gen = this.stack[this.stack.length - 1]; 245 | if (this.gen.history === undefined) this.gen.history = []; 246 | 247 | var result; 248 | if (retval instanceof Exception) { 249 | result = this.gen.throw(retval); //THROW METHOD OF THE GENERATOR IS CALLED, WHICH IS SENT TO CALLER AS thrown EXCEPTION 250 | } else { 251 | result = this.gen.next(retval) 252 | }//endif 253 | retval = result.value; 254 | } catch (e) { 255 | retval = Exception.wrap(e); 256 | } finally { 257 | Thread.currentThread = selfThread; 258 | }//try 259 | }//while 260 | //CAN GET HERE WHEN THREAD IS KILLED AND Thread.Resume CALLS BACK 261 | this.kill(retval); 262 | };//function 263 | 264 | //THIS IS A MESS, CALLED FROM DIFFERENT LOCATIONS, AND MUST DISCOVER 265 | //CONTEXT TO RUN CORRECT CODE 266 | //retval===undefined - NORMAL KILL 267 | //retval===true - TOTAL KILL, NO TRY/CATCH (REALLY BAD) SUPPRESS THREAD EXCEPTION 268 | //retval instanceof Exception - THROW SPECIFIC THREAD EXCEPTION 269 | Thread.prototype.kill = function(retval){ 270 | 271 | var children = this.children.slice(); //CHILD THREAD WILL REMOVE THEMSELVES FROM THIS LIST 272 | // Log.note("Killing "+convert.value2json(children.select("name"))+" child threads"); 273 | for (var c = 0; c < children.length; c++) { 274 | var child = children[c]; 275 | if (!child) continue; 276 | try { 277 | if (child.kill) { 278 | child.kill(); 279 | } else if (child.abort) { 280 | child.abort(); 281 | }//endif 282 | } catch (e) { 283 | Log.error("kill?", child) 284 | }//try 285 | }//for 286 | 287 | if (this.stack.length > 0) { 288 | if (retval == true) { 289 | while (this.stack.length > 0) { 290 | try { 291 | var g = this.stack.pop(); 292 | if (g.close) g.close(); //PREMATURE CLOSE, REALLY BAD 293 | } catch (e) { 294 | //DO NOTHING 295 | }//try 296 | }//while 297 | this.threadResponse = Thread.Interrupted; 298 | } else { 299 | this.stack.push(DUMMY_GENERATOR); //TOP OF STACK IS THE RUNNING GENERATOR, THIS kill() CAME FROM BEYOND 300 | this.threadResponse = this.resume(Thread.Interrupted); //RUN THE EXCEPTION HANDLER RIGHT NOW 301 | }//endif 302 | 303 | if (this.stack.length > 0) { 304 | Log.error("Expecting thread " + self.name + " to have dealt with kill() immediately"); 305 | }//endif 306 | }//endif 307 | this.stack = []; 308 | this.keepRunning = false; 309 | 310 | this.parentThread.children.remove(this); 311 | Thread.isRunning.remove(this); 312 | 313 | if (Thread.isRunning.length == 0) { 314 | Thread.hideWorking(); 315 | }//endif 316 | }; 317 | 318 | //ASSUME THERE IS NO MORE STUFF FOR THREAD TO DO 319 | Thread.prototype.shutdown = function(retval){ 320 | this.threadResponse = retval; //REMEMBER FOR THREAD THAT JOINS WITH THIS 321 | this.keepRunning = false; 322 | 323 | this.parentThread.children.remove(this); 324 | Thread.isRunning.remove(this); 325 | 326 | if (Thread.isRunning.length == 0) { 327 | Thread.hideWorking(); 328 | }//endif 329 | 330 | if (retval instanceof Exception) { 331 | if (POPUP_ON_ERROR || DEBUG) { 332 | var details = retval.toString(); 333 | if (details == "[object Object]") details = retval.message; 334 | Log.alert("Uncaught Error in thread: " + coalesce(this.name, "") + "\n " + details); 335 | } else { 336 | Log.warning("Uncaught Error in thread: " + coalesce(this.name, "") + "\n ", retval); 337 | }//endif 338 | }//endif 339 | 340 | return retval; 341 | }; 342 | 343 | 344 | //var stackPattern=/(.*)@(.*):(\d+):(\d+)/; 345 | //function parseStack(stackString){ 346 | // var output = []; 347 | // if (stackString===undefined || stackString==null) return output; 348 | // stackString.split("\n").forEach(function(line){ 349 | // var parts=stackPattern.exec(line); 350 | // if (parts==null) return; 351 | // output.push({ 352 | // "function":parts[1], 353 | // "fileName":parts[2], 354 | // "lineNumber":parts[3], 355 | // "columnNumber":parts[4] 356 | // }); 357 | // }); 358 | // return output; 359 | //}//function 360 | // 361 | ////PUT AT THE BEGINNING OF A GENERATOR TO ENSURE IT WILL ONLY BE CALLED USING yield() 362 | //Thread.assertThreaded = function(){ 363 | // var caller = null; 364 | // try{ 365 | // throw Error(); 366 | // }catch (e){ 367 | // //THIS IS A BETTER PATH, GIVEN SOME IMPORTED JS FILE CAN CALL importScript() DIRECTLY 368 | // caller = parseStack(e.stack)[1].function; 369 | // }//try 370 | // 371 | // //GET CALLER AND DETERMINE IF RUNNING IN THREADED MODE 372 | // if (caller != "Thread_prototype_resume") 373 | // Log.error("must call from a thread as \"yield (GUI.refresh());\" "); 374 | //};//method 375 | 376 | //PUT AT THE BEGINNING OF A GENERATOR TO ENSURE IT WILL ONLY BE CALLED USING yield() 377 | Thread.assertThreaded = function(){ 378 | //GET CALLER AND DETERMINE IF RUNNING IN THREADED MODE 379 | if (arguments["callee"].caller.caller.name != "Thread_prototype_resume") 380 | Log.error("must call from a thread as \"yield (GUI.refresh());\" "); 381 | };//method 382 | 383 | 384 | //DO NOT RESUME FOR A WHILE 385 | Thread.sleep = function*(millis){ 386 | var resume = yield(Thread.Resume); 387 | 388 | if (DEBUG) { 389 | var threadName = Thread.currentThread.name; 390 | var temp = resume; 391 | resume = function(){ 392 | Log.note("done timeout of " + millis + ", resuming thread " + threadName); 393 | temp() 394 | }; 395 | }//endif 396 | 397 | var to = setTimeout(resume, millis); 398 | yield (Thread.suspend({ 399 | "kill": function(){ 400 | clearTimeout(to); 401 | } 402 | })) 403 | }; 404 | 405 | //LET THE MAIN EVENT LOOP GET SOME ACTION 406 | // CALLING yield (Thread.YIELD) IS FASTER THAN yield (Thread.yield()) 407 | Thread.yield = function*(){ 408 | yield (YIELD); 409 | }; 410 | 411 | //NEW SUSPEND OBJECT 412 | Thread.suspend = function(request){ 413 | if (request !== undefined) { 414 | if (request.kill === undefined) { 415 | if (request.abort === undefined) { 416 | Log.error("Expecting an object with kill() or abort() function"); 417 | } else { 418 | request.kill = function(){ 419 | this.abort(); 420 | };//function 421 | }//endif 422 | }//endif 423 | }//endif 424 | return new Suspend(request); 425 | }; 426 | 427 | 428 | //RETURNS A GENERATOR, BE SURE TO yield IT 429 | Thread.prototype.join = function(timeout){ 430 | return Thread.join(this, timeout); 431 | }; 432 | 433 | 434 | /* 435 | * RESUME WHEN ANY THREAD IN LIST IS COMPLETE (FAIL, OR NOT), IGNORE THE REST 436 | */ 437 | Thread.joinAny = function*(otherThreads){ 438 | var resumeCurrentThread = yield(Thread.Resume); 439 | 440 | var immediateResponse = (function(resumeCurrentThread){ 441 | for (var i = 0; i < otherThreads.length; i++) { 442 | var otherThread = otherThreads[i]; 443 | if (!otherThread.keepRunning) { 444 | resumeCurrentThread = null; 445 | return otherThread.threadResponse; 446 | }//endif 447 | 448 | //WE WILL SIMPLY MAKE THE JOINING THREAD LOOK LIKE THE otherThread's CALLER 449 | //(WILL ALSO PACKAGE ANY EXCEPTIONS THAT ARE THROWN FROM otherThread) 450 | var gen = threadResumeOnJoin(otherThread, function(retval){ 451 | if (resumeCurrentThread) { 452 | var temp = resumeCurrentThread; 453 | resumeCurrentThread = null; 454 | temp(retval) 455 | }//endif 456 | }); 457 | gen.next(); //THE FIRST CALL TO next() 458 | otherThread.stack.unshift(gen); 459 | if (DEBUG) { 460 | Log.note("pausing thread " + Thread.currentThread.name + " while joining " + otherThread.name) 461 | }//endif 462 | }//for 463 | return undefined; 464 | })(resumeCurrentThread); 465 | 466 | if (immediateResponse === undefined) { 467 | yield (Thread.suspend()); 468 | } else { 469 | yield (immediateResponse); 470 | }//endif 471 | }; 472 | 473 | //WAIT FOR OTHER THREAD TO FINISH 474 | Thread.join = function*(otherThread, timeout){ 475 | var children = otherThread.children.slice(); //copy 476 | for (var c = 0; c < children.length; c++) { 477 | var childThread = children[c]; 478 | if (!(childThread instanceof Thread)) continue; 479 | 480 | yield Thread.join(childThread, timeout); 481 | }//for 482 | 483 | 484 | if (timeout === undefined) { 485 | if (DEBUG) 486 | while (otherThread.keepRunning) { 487 | yield(Thread.sleep(1000)); 488 | if (otherThread.keepRunning) 489 | Log.note("Waiting for thread"); 490 | }//while 491 | 492 | if (otherThread.keepRunning) { 493 | //WE WILL SIMPLY MAKE THE JOINING THREAD LOOK LIKE THE otherThread's CALLER 494 | //(WILL ALSO PACKAGE ANY EXCEPTIONS THAT ARE THROWN FROM otherThread) 495 | var resumeWhenDone = yield(Thread.Resume); 496 | var gen = threadResumeOnJoin(otherThread, resumeWhenDone); 497 | gen.next(); //THE FIRST CALL TO next() 498 | otherThread.stack.unshift(gen); 499 | if (DEBUG) { 500 | Log.note("pausing thread " + Thread.currentThread.name + " while joining " + otherThread.name) 501 | } 502 | yield (Thread.suspend()); 503 | } else { 504 | yield (otherThread.threadResponse); 505 | }//endif 506 | } else { 507 | //WE SHOULD USE A REAL SIGNAL, BUT I AM LAZY SO WE BUSY-WAIT 508 | for (var t = 0; t < 10; t++) { 509 | if (otherThread.keepRunning) { 510 | yield(Thread.sleep(timeout / 10)); 511 | }//endif 512 | }//for 513 | }//endif 514 | }; 515 | 516 | 517 | //THIS GENERATOR EXPECTS send TO BE CALLED TWICE ONLY 518 | //FIRST WITH NO PARAMETERS, AS REQUIRED BY ALL GENERATORS 519 | //THE SEND RUN FROM THE JOINING THREAD TO RETURN THE VALUE 520 | function* threadResumeOnJoin(otherThread, resumeFunction){ 521 | var result; 522 | try { 523 | result = yield(undefined); 524 | } catch (e) { 525 | if (POPUP_ON_ERROR || DEBUG) { 526 | Log.alert("Uncaught Error in thread: " + (otherThread.name !== undefined ? otherThread.name : "") + "\n " + e.toString()); 527 | } else { 528 | Log.warning("Uncaught Error in thread: " + (otherThread.name !== undefined ? otherThread.name : "") + "\n ", e); 529 | }//endif 530 | 531 | result = e 532 | }//try 533 | resumeFunction(result); //PACK TO HIDE EXCEPTION 534 | }//method 535 | 536 | //CALL THE funcTION WITH THE GIVEN PARAMETERS 537 | //WILL ADD success AND error FUNCTIONS TO param TO CAPTURE RESPONSE 538 | Thread.call = function*(func, param){ 539 | param.success = yield(Thread.Resume); 540 | param.error = function(){ 541 | throw new Exception("callback to func was error:\n\t" + window.JSON.stringify(arguments), undefined); 542 | }; 543 | var instance = func(param); 544 | yield (new Suspend(instance)); 545 | };//method 546 | 547 | 548 | }; 549 | 550 | 551 | if (window.Exception === undefined) { 552 | 553 | window.Exception = function(message, cause){ 554 | this.message = message; 555 | this.cause = cause; 556 | }; 557 | 558 | window.Exception.wrap = function(e){ 559 | if (e instanceof Exception) { 560 | return e; 561 | } else { 562 | return new Exception("Error", e); 563 | }//endif 564 | }; 565 | 566 | Array.prototype.remove = function(obj, start){ 567 | while (true) { 568 | var i = this.indexOf(obj, start); 569 | if (i == -1) return this; 570 | this.splice(i, 1); 571 | }//while 572 | }; 573 | 574 | } 575 | 576 | if (!window.Log) { 577 | Log = {}; 578 | Log.error = function(mess, cause){ 579 | console.error(mess); 580 | throw new Exception(mess, cause); 581 | }; 582 | Log.warning = console.warn; 583 | Log.note = Log.note = function(v){ 584 | console.log(v); 585 | }; 586 | }//endif 587 | 588 | 589 | build(); 590 | 591 | -------------------------------------------------------------------------------- /tests/AjaxInterrupt.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /tests/AjaxKill.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /tests/JoinAny.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | Many JSON Calls 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |

Call Flickr's public API from multiple threads, show fastest response only

17 | 18 |
19 | Spinner to show insignificant blocking: 20 |
21 |
22 |
23 | 24 | 25 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /tests/JoinWithDelayedError.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /tests/JoinWithError.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /tests/Parallel.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | Many JSON Calls 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |

Call Flickr's public API from multiple threads

17 | 18 |
19 | Spinner to show insignificant blocking: 20 |
21 |
22 |
23 | 24 | 25 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /tests/Serial.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | Serial Calls 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |

Call Flickr's public API for each tag, one at a time

16 | 17 |
18 | Spinner to show insignificant blocking: 19 |
20 |
21 | 22 |
23 | 24 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /tests/SimpleReturn.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /tests/TightLoop.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | Many JSON Calls 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 |

Count Fast Without Blocking

18 | 19 |
20 | 21 |
22 | Spinner to show insignificant blocking: 23 |
24 |
25 | 26 | 27 | 28 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /tests/YieldInterrupt.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /tests/lib/debug.js: -------------------------------------------------------------------------------- 1 | function GOOD(message) { 2 | $("body").append("

Success: " + message + "

"); 3 | } 4 | function ERROR(message) { 5 | $("body").append("

Failure: " + message + "

"); 6 | } 7 | 8 | 9 | if (!window.Log){ 10 | Log = {}; 11 | Log.error = function(mess, cause){ 12 | console.error(mess); 13 | throw new Exception(mess, cause); 14 | }; 15 | Log.alert = function(mess){ 16 | Log.note("************************************************************\n" + mess + top); 17 | }; 18 | Log.warning = console.warn; 19 | Log.note = function(v){console.log(v);}; 20 | }//endif 21 | 22 | -------------------------------------------------------------------------------- /tests/lib/flickr.js: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | 6 | var NUM_IMAGES = 5; 7 | 8 | 9 | // PUT FLICKR IMAGES INTO A ROW OF A TABLE 10 | function displayImages(data, tag) { 11 | var html = "" + tag + "" + $.map(data.items, function (item, i) { 12 | if (i > NUM_IMAGES) return ""; 13 | 14 | var img = (item.media.m).replace("_m.jpg", "_s.jpg"); 15 | return '' + 16 | '' + 17 | ''; 18 | }) + ""; 19 | $('#images').append(html); 20 | } 21 | -------------------------------------------------------------------------------- /tests/lib/spin.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2011-2013 Felix Gnass 3 | * Licensed under the MIT license 4 | */ 5 | (function (root, factory) { 6 | 7 | /* CommonJS */ 8 | if (typeof exports == 'object') module.exports = factory() 9 | 10 | /* AMD module */ 11 | else if (typeof define == 'function' && define.amd) define(factory) 12 | 13 | /* Browser global */ 14 | else root.Spinner = factory() 15 | } 16 | (this, function () { 17 | "use strict"; 18 | 19 | var prefixes = ['webkit', 'Moz', 'ms', 'O'] /* Vendor prefixes */ 20 | , animations = {} /* Animation rules keyed by their name */ 21 | , useCssAnimations 22 | /* Whether to use CSS animations or setTimeout */ 23 | 24 | /** 25 | * Utility function to create elements. If no tag name is given, 26 | * a DIV is created. Optionally properties can be passed. 27 | */ 28 | function createEl(tag, prop) { 29 | var el = document.createElement(tag || 'div') 30 | , n 31 | 32 | for (n in prop) el[n] = prop[n] 33 | return el 34 | } 35 | 36 | /** 37 | * Appends children and returns the parent. 38 | */ 39 | function ins(parent /* child1, child2, ...*/) { 40 | for (var i = 1, n = arguments.length; i < n; i++) 41 | parent.appendChild(arguments[i]) 42 | 43 | return parent 44 | } 45 | 46 | /** 47 | * Insert a new stylesheet to hold the @keyframe or VML rules. 48 | */ 49 | var sheet = (function () { 50 | var el = createEl('style', {type: 'text/css'}) 51 | ins(document.getElementsByTagName('head')[0], el) 52 | return el.sheet || el.styleSheet 53 | }()) 54 | 55 | /** 56 | * Creates an opacity keyframe animation rule and returns its name. 57 | * Since most mobile Webkits have timing issues with animation-delay, 58 | * we create separate rules for each line/segment. 59 | */ 60 | function addAnimation(alpha, trail, i, lines) { 61 | var name = ['opacity', trail, ~~(alpha * 100), i, lines].join('-') 62 | , start = 0.01 + i / lines * 100 63 | , z = Math.max(1 - (1 - alpha) / trail * (100 - start), alpha) 64 | , prefix = useCssAnimations.substring(0, useCssAnimations.indexOf('Animation')).toLowerCase() 65 | , pre = prefix && '-' + prefix + '-' || '' 66 | 67 | if (!animations[name]) { 68 | sheet.insertRule( 69 | '@' + pre + 'keyframes ' + name + '{' + 70 | '0%{opacity:' + z + '}' + 71 | start + '%{opacity:' + alpha + '}' + 72 | (start + 0.01) + '%{opacity:1}' + 73 | (start + trail) % 100 + '%{opacity:' + alpha + '}' + 74 | '100%{opacity:' + z + '}' + 75 | '}', sheet.cssRules.length) 76 | 77 | animations[name] = 1 78 | } 79 | 80 | return name 81 | } 82 | 83 | /** 84 | * Tries various vendor prefixes and returns the first supported property. 85 | */ 86 | function vendor(el, prop) { 87 | var s = el.style 88 | , pp 89 | , i 90 | 91 | prop = prop.charAt(0).toUpperCase() + prop.slice(1) 92 | for (i = 0; i < prefixes.length; i++) { 93 | pp = prefixes[i] + prop 94 | if (s[pp] !== undefined) return pp 95 | } 96 | if (s[prop] !== undefined) return prop 97 | } 98 | 99 | /** 100 | * Sets multiple style properties at once. 101 | */ 102 | function css(el, prop) { 103 | for (var n in prop) 104 | el.style[vendor(el, n) || n] = prop[n] 105 | 106 | return el 107 | } 108 | 109 | /** 110 | * Fills in default values. 111 | */ 112 | function merge(obj) { 113 | for (var i = 1; i < arguments.length; i++) { 114 | var def = arguments[i] 115 | for (var n in def) 116 | if (obj[n] === undefined) obj[n] = def[n] 117 | } 118 | return obj 119 | } 120 | 121 | /** 122 | * Returns the absolute page-offset of the given element. 123 | */ 124 | function pos(el) { 125 | var o = { x: el.offsetLeft, y: el.offsetTop } 126 | while ((el = el.offsetParent)) 127 | o.x += el.offsetLeft, o.y += el.offsetTop 128 | 129 | return o 130 | } 131 | 132 | /** 133 | * Returns the line color from the given string or array. 134 | */ 135 | function getColor(color, idx) { 136 | return typeof color == 'string' ? color : color[idx % color.length] 137 | } 138 | 139 | // Built-in defaults 140 | 141 | var defaults = { 142 | lines: 12, // The number of lines to draw 143 | length: 7, // The length of each line 144 | width: 5, // The line thickness 145 | radius: 10, // The radius of the inner circle 146 | rotate: 0, // Rotation offset 147 | corners: 1, // Roundness (0..1) 148 | color: '#000', // #rgb or #rrggbb 149 | direction: 1, // 1: clockwise, -1: counterclockwise 150 | speed: 1, // Rounds per second 151 | trail: 100, // Afterglow percentage 152 | opacity: 1 / 4, // Opacity of the lines 153 | fps: 20, // Frames per second when using setTimeout() 154 | zIndex: 2e9, // Use a high z-index by default 155 | className: 'spinner', // CSS class to assign to the element 156 | top: 'auto', // center vertically 157 | left: 'auto', // center horizontally 158 | position: 'relative' // element position 159 | } 160 | 161 | /** The constructor */ 162 | function Spinner(o) { 163 | if (typeof this == 'undefined') return new Spinner(o) 164 | this.opts = merge(o || {}, Spinner.defaults, defaults) 165 | } 166 | 167 | // Global defaults that override the built-ins: 168 | Spinner.defaults = {} 169 | 170 | merge(Spinner.prototype, { 171 | 172 | /** 173 | * Adds the spinner to the given target element. If this instance is already 174 | * spinning, it is automatically removed from its previous target b calling 175 | * stop() internally. 176 | */ 177 | spin: function (target) { 178 | this.stop() 179 | 180 | var self = this 181 | , o = self.opts 182 | , el = self.el = css(createEl(0, {className: o.className}), {position: o.position, width: 0, zIndex: o.zIndex}) 183 | , mid = o.radius + o.length + o.width 184 | , ep // element position 185 | , tp // target position 186 | 187 | if (target) { 188 | target.insertBefore(el, target.firstChild || null) 189 | tp = pos(target) 190 | ep = pos(el) 191 | css(el, { 192 | left: (o.left == 'auto' ? tp.x - ep.x + (target.offsetWidth >> 1) : parseInt(o.left, 10) + mid) + 'px', 193 | top: (o.top == 'auto' ? tp.y - ep.y + (target.offsetHeight >> 1) : parseInt(o.top, 10) + mid) + 'px' 194 | }) 195 | } 196 | 197 | el.setAttribute('role', 'progressbar') 198 | self.lines(el, self.opts) 199 | 200 | if (!useCssAnimations) { 201 | // No CSS animation support, use setTimeout() instead 202 | var i = 0 203 | , start = (o.lines - 1) * (1 - o.direction) / 2 204 | , alpha 205 | , fps = o.fps 206 | , f = fps / o.speed 207 | , ostep = (1 - o.opacity) / (f * o.trail / 100) 208 | , astep = f / o.lines 209 | 210 | ; 211 | (function anim() { 212 | i++; 213 | for (var j = 0; j < o.lines; j++) { 214 | alpha = Math.max(1 - (i + (o.lines - j) * astep) % f * ostep, o.opacity) 215 | 216 | self.opacity(el, j * o.direction + start, alpha, o) 217 | } 218 | self.timeout = self.el && setTimeout(anim, ~~(1000 / fps)) 219 | })() 220 | } 221 | return self 222 | }, 223 | 224 | /** 225 | * Stops and removes the Spinner. 226 | */ 227 | stop: function () { 228 | var el = this.el 229 | if (el) { 230 | clearTimeout(this.timeout) 231 | if (el.parentNode) el.parentNode.removeChild(el) 232 | this.el = undefined 233 | } 234 | return this 235 | }, 236 | 237 | /** 238 | * Internal method that draws the individual lines. Will be overwritten 239 | * in VML fallback mode below. 240 | */ 241 | lines: function (el, o) { 242 | var i = 0 243 | , start = (o.lines - 1) * (1 - o.direction) / 2 244 | , seg 245 | 246 | function fill(color, shadow) { 247 | return css(createEl(), { 248 | position: 'absolute', 249 | width: (o.length + o.width) + 'px', 250 | height: o.width + 'px', 251 | background: color, 252 | boxShadow: shadow, 253 | transformOrigin: 'left', 254 | transform: 'rotate(' + ~~(360 / o.lines * i + o.rotate) + 'deg) translate(' + o.radius + 'px' + ',0)', 255 | borderRadius: (o.corners * o.width >> 1) + 'px' 256 | }) 257 | } 258 | 259 | for (; i < o.lines; i++) { 260 | seg = css(createEl(), { 261 | position: 'absolute', 262 | top: 1 + ~(o.width / 2) + 'px', 263 | transform: o.hwaccel ? 'translate3d(0,0,0)' : '', 264 | opacity: o.opacity, 265 | animation: useCssAnimations && addAnimation(o.opacity, o.trail, start + i * o.direction, o.lines) + ' ' + 1 / o.speed + 's linear infinite' 266 | }) 267 | 268 | if (o.shadow) ins(seg, css(fill('#000', '0 0 4px ' + '#000'), {top: 2 + 'px'})) 269 | ins(el, ins(seg, fill(getColor(o.color, i), '0 0 1px rgba(0,0,0,.1)'))) 270 | } 271 | return el 272 | }, 273 | 274 | /** 275 | * Internal method that adjusts the opacity of a single line. 276 | * Will be overwritten in VML fallback mode below. 277 | */ 278 | opacity: function (el, i, val) { 279 | if (i < el.childNodes.length) el.childNodes[i].style.opacity = val 280 | } 281 | 282 | }) 283 | 284 | 285 | function initVML() { 286 | 287 | /* Utility function to create a VML tag */ 288 | function vml(tag, attr) { 289 | return createEl('<' + tag + ' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">', attr) 290 | } 291 | 292 | // No CSS transforms but VML support, add a CSS rule for VML elements: 293 | sheet.addRule('.spin-vml', 'behavior:url(#default#VML)') 294 | 295 | Spinner.prototype.lines = function (el, o) { 296 | var r = o.length + o.width 297 | , s = 2 * r 298 | 299 | function grp() { 300 | return css( 301 | vml('group', { 302 | coordsize: s + ' ' + s, 303 | coordorigin: -r + ' ' + -r 304 | }), 305 | { width: s, height: s } 306 | ) 307 | } 308 | 309 | var margin = -(o.width + o.length) * 2 + 'px' 310 | , g = css(grp(), {position: 'absolute', top: margin, left: margin}) 311 | , i 312 | 313 | function seg(i, dx, filter) { 314 | ins(g, 315 | ins(css(grp(), {rotation: 360 / o.lines * i + 'deg', left: ~~dx}), 316 | ins(css(vml('roundrect', {arcsize: o.corners}), { 317 | width: r, 318 | height: o.width, 319 | left: o.radius, 320 | top: -o.width >> 1, 321 | filter: filter 322 | }), 323 | vml('fill', {color: getColor(o.color, i), opacity: o.opacity}), 324 | vml('stroke', {opacity: 0}) // transparent stroke to fix color bleeding upon opacity change 325 | ) 326 | ) 327 | ) 328 | } 329 | 330 | if (o.shadow) 331 | for (i = 1; i <= o.lines; i++) 332 | seg(i, -2, 'progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)') 333 | 334 | for (i = 1; i <= o.lines; i++) seg(i) 335 | return ins(el, g) 336 | } 337 | 338 | Spinner.prototype.opacity = function (el, i, val, o) { 339 | var c = el.firstChild 340 | o = o.shadow && o.lines || 0 341 | if (c && i + o < c.childNodes.length) { 342 | c = c.childNodes[i + o]; 343 | c = c && c.firstChild; 344 | c = c && c.firstChild 345 | if (c) c.opacity = val 346 | } 347 | } 348 | } 349 | 350 | var probe = css(createEl('group'), {behavior: 'url(#default#VML)'}) 351 | 352 | if (!vendor(probe, 'transform') && probe.adj) initVML() 353 | else useCssAnimations = vendor(probe, 'animation') 354 | 355 | return Spinner 356 | 357 | })); 358 | -------------------------------------------------------------------------------- /tests/lib/spinner.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | var opts = { 3 | lines: 7, // The number of lines to draw 4 | length: 5, // The length of each line 5 | width: 4, // The line thickness 6 | radius: 5, // The radius of the inner circle 7 | corners: 1, // Corner roundness (0..1) 8 | rotate: 0, // The rotation offset 9 | direction: 1, // 1: clockwise, -1: counterclockwise 10 | color: '#000', // #rgb or #rrggbb 11 | speed: 2, // Rounds per second 12 | trail: 60, // Afterglow percentage 13 | shadow: false, // Whether to render a shadow 14 | hwaccel: false, // Whether to use hardware acceleration 15 | className: 'spinner', // The CSS class to assign to the spinner 16 | zIndex: 2e9, // The z-index (defaults to 2000000000) 17 | top: 'auto', // Top position relative to parent in px 18 | left: 'auto' // Left position relative to parent in px 19 | }; 20 | 21 | 22 | $("#spinner").css({ 23 | "vertical-align": "text-bottom", 24 | "display": "inline-block", 25 | "height": "20px", 26 | "width": "20px" 27 | }); 28 | new Spinner(opts).spin(document.getElementById("spinner")); 29 | 30 | }); 31 | 32 | --------------------------------------------------------------------------------