Skip to content

Instantly share code, notes, and snippets.

@pchng
Last active August 29, 2015 13:57
Show Gist options
  • Save pchng/9360152 to your computer and use it in GitHub Desktop.
Save pchng/9360152 to your computer and use it in GitHub Desktop.
Demonstration of JavaScript single-threadedness
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test of JavaScript single-threadedness</title>
</head>
<body>
<h1>Test of JavaScript single-threadedness</h1>
<button id="check">Check</button>
<script src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
<pre id="output"></pre>
<script>
$("#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) {
$('#output').empty().append(
'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:
// https://developer.mozilla.org/en/docs/Web/API/window.setTimeout#Minimum.2F_maximum_delay_and_timeout_nesting
// while(!output)
// ;
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment