Core JavaScript

Worker with Messaging

This JavaScript code example demonstrates how to program a multithreaded worker with messaging.

WorkerWithMessaging.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>XoaX.net's JavaScript Web Workers Demo</title>
		<style type="text/css">
			#idLastPrime {
				color: green;
				font-family: monospace;
			}
		</style>
		<script type="text/javascript">
			function Initialization() {
				var qWorker = new Worker('WorkerWithMessaging.js');
				qWorker.onmessage = function (qEvent) {
					document.getElementById('idLastPrime').textContent = qEvent.data;
				}
			}
		</script>
	</head>
	<body onload="Initialization()">
		<p>Prime Number: <span id="idLastPrime"></span></p>
	</body>
</html>

WorkerWithMessaging.js

// NOTE: THIS REQUIRES A WEB SERVER TO RUN
var giNatural = 1;
GotoIncrement: while (giNatural <= 10000000) {
	++giNatural;
	for (let iDivisor = 2; iDivisor <= Math.sqrt(giNatural); ++iDivisor) {
		// If the divisor divides the natural number, it is not prime. So, go the next one.
		if (giNatural % iDivisor == 0) {
			continue GotoIncrement;
		}
	}
	// If the for loop ends, record the prime number.
	postMessage(giNatural);
}
 

Output

 
 

© 2007–2026 XoaX.net LLC. All rights reserved.