Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Demonstration of JavaScript single-threadedness
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Test of JavaScript single-threadedness</title>
<h1>Test of JavaScript single-threadedness</h1>
<button id="check">Check</button>
<script src=""></script>
<pre id="output"></pre>
$("#check").click(function(e) {
console.log('Length of output: %s', output.length);
var matches_ab = output.match(/ab/g);
console.log('Number of occurences of "ab": %s', matches_ab.length);
var matches_ba = output.match(/ba/g);
console.log('Was "ba" found? %s', !!matches_ba);
var didSetTimeoutFunctionBlock = (1 == matches_ab.length) && !matches_ba;
console.log('Did the functions called by setTimeout() block? %s', didSetTimeoutFunctionBlock);
if (didSetTimeoutFunctionBlock) {
'The output consists of a solid block of "a" followed by a solid block of "b".\n' +
'This indicates that the first function executed entirely before the second function.\n'
// NOTE: Might crash your browser if iterations is too high.
var output = '';
var iterations = 10000000;
setTimeout(function() {
for (var i = 0; i < iterations; ++i) {
output += 'a';
}, 100);
setTimeout(function() {
for (var i = 0; i < iterations; ++i) {
output += 'b';
}, 100);
// NOTE: We can't have this while loop in order to "wait" for the output to have some text
// from the functions invoked by the setTimeout() calls above, because it will actually block
// and prevent the execution of the functions passed into setTimeout():
// Minimum delay:
// while(!output)
// ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment