Labs/JS Modules: Difference between revisions

document the new Sync module
(document the new Sync module)
Line 313: Line 313:
   dump(string.key + " = " + string.value + "\n");
   dump(string.key + " = " + string.value + "\n");
  }
  }
== Sync ==
The [http://hg.mozdev.org/jsmodules/file/tip/Sync.js Sync module] provides a simple way to write asynchronous code in a sequential, callback-free fashion that looks like synchronous code. It also provides a sleep function written using its functionality.
Using the sleep function is really easy. Just import the module, which adds the Sync symbol to your namespace, then call its Sync.sleep method:
Components.utils.import("resource://path/to/Sync.js");
Sync.sleep(1000); // sleep 1000 milliseconds
You can create your own such "synchronous asynchronous" function by adding the Sync.sync method to the Function prototype and calling it wherever you would normally call your function. Your function must then accept a callback as its first argument that it calls once it is done with its asynchronous work.
Here's how to implement and then call your own sleep function:
Components.utils.import("resource://path/to/Sync.js");
Function.prototype.sync = Sync.sync;
function sleep(callback, milliseconds) {
  setTimeout(callback, milliseconds);
}
sleep.sync(1000); // sleep 1000 milliseconds


== URI ==
== URI ==
canmove, Confirmed users
2,056

edits