Skip to content

Instantly share code, notes, and snippets.

@tcw165
Last active August 30, 2015 13:54
Show Gist options
  • Save tcw165/b064e727b5573e0260e9 to your computer and use it in GitHub Desktop.
Save tcw165/b064e727b5573e0260e9 to your computer and use it in GitHub Desktop.
Experiment for testing the "Concurrency Model and Event Loop" of JavaScript.
/**
* This is an experiment for testing the "Concurrency Model and Event Loop" of
* JavaScript.
*
* It's designed that an asynchronous function with a given callback is called;
* And subsequently a synchronous function which is designated to take far more
* time than the asynchronous one will take is called.
*
* Question: what is the response order of async-fun/sync-fun/callback?
*
* Answer: JavaScript runtime contains a message queue which stores a list of
* messages to be processed and their associated callback functions. The main
* thread is taken as a message queued with toppest executing priority. And
* JavaScript runtime process each message completely before any other message
* is processed. This differs from C, for instance, where if a function runs in
* a thread, it can be stopped at any point to run some other code in another
* thread.
* In the example, even the asynchronous callback takes far less time to finish
* than the synchronous function will take. The async-function is called first;
* and the sync-function is called secondly; then the callback is called lastly.
*
* Usage
* -----
* node ConcurrencyModelOfJavaScript.js
*
* Reference
* ---------
* - http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained
* - https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
*/
var http = require('http');
var countDown = Math.pow(2, 30);
function syncWait(loop) {
var counter = loop;
while (counter-- >= 0);
}
console.time('Asynchronous function called (with callback).');
http.get({host: 'www.google.com'}, function(res) {
console.log('Asynchronous callback called. res.statusCode = %s', res.statusCode);
});
console.timeEnd('Asynchronous function called (with callback).');
console.time('Synchronous function called.');
syncWait(countDown);
console.timeEnd('Synchronous function called.');
// output example:
// Asynchronous function called (with callback).: 5ms
// Synchronous function called.: 1260ms
// Asynchronous callback called. res.statusCode = 302
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment