Core JavaScript

Transfering an ArrayBuffer

This example demonstrates how to create a worker and transfer an ArrayBuffer to it and receive the ArrayBuffer back from it. An arithmetic series of values that is returned in the buffer is added to the table as a new row of the table.

ArithmeticTableRows.html

<!DOCTYPE html>
<html>
	<head>
  	<title>XoaX.net's Javascript</title>
  	<script type="text/javascript" src="ArithmeticTableRows.js"></script>
  	<style>
  	#idArithmeticTable, th, td {
  		border: 1px black solid;
  	}
  	</style>
	</head>
	<body onload="Initialize()">
		<table id="idArithmeticTable" cellspacing="2" cellpadding="5" border="3">
			<tr><th>A0</th><th>A1</th><th>A2</th><th>A3</th><th>A4</th><th>A5</th><th>A6</th><th>A7</th></tr>
		</table>
	</body>
</html>

ArithmeticTableRows.js

// NOTE: THIS REQUIRES A WEB SERVER TO RUN
function Initialize() {
	// Create a worker
	var qWorker = new Worker("MakeArithmeticSequence.js");
	qWorker.onmessage = function(qEvent) {
		// Create a row element
		var qNewRow = document.createElement("tr");
		// Create an array to hold the buffer
		var i8aArray = new Int8Array(qEvent.data.mdaBuffer);
		for (var i = 0; i < i8aArray.length; ++i) {
			// Create a new data element, fill it with the value and add it to the row
			var qNewData = document.createElement("td");
			qNewData.innerHTML = i8aArray[i];
			qNewRow.appendChild(qNewData);
		}
		// Get the table element
		var qTable = document.getElementById("idArithmeticTable");
		qTable.appendChild(qNewRow);
	}
	var qArithSeq = {mdA0:5, mdD:3};
	qArithSeq.mdaBuffer = new ArrayBuffer(8);
	// Give control of the buffer to the worker
	qWorker.postMessage(qArithSeq, [qArithSeq.mdaBuffer]);

}

MakeArithmeticSequence.js

onmessage = function(qEvent) {
	// Get the initial value
	var dA0 = qEvent.data.mdA0;
	// Get the difference
	var dD = qEvent.data.mdD;
	// Create a new array to hold the buffer
	var i8aArray = new Int8Array(qEvent.data.mdaBuffer);
	// Generate the sequence in the array
	for (var i = 0; i < i8aArray.length; ++i) {
		i8aArray[i] = dA0 + i*dD;
	}
	var qArithSeq = {mdA0:5, mdD:3};
	qArithSeq.mdaBuffer = qEvent.data.mdaBuffer
	postMessage(qArithSeq, [qArithSeq.mdaBuffer]);
}
 

Output

 
 

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