Javascript Course


Web Worker is a JavaScript object running in the background, without affecting the performance of the page. The worker thread can perform tasks without interfering with the user interface.
You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

Creating a Web Worker

Generally, a JavaScript web worker is created in a separated file on server, for exampe worker.js. This file contains the code that will run in the worker thread.

You can run whatever JS code you like inside the worker file, with some exceptions.
You can't directly manipulate the DOM from inside a worker, or use default methods and properties of the window, document, and parent objects. But you can use a large number of items available under window, including: XMLHttpRequest (Ajax), WebSockets, Navigator and IndexedDB.

In the page where you want to use the web worker, create an Worker object instance with this syntax.

if(window.Worker){
 var wrk = new Worker('worker.js');
}
- Once created a JS code in the worker.js file (or whatever name you want), it can send messages to the JavaScript code that created the Worker instance.

Data is sent between workers and the main thread via a system of messages — both sides send their messages using the postMessage() method, and can get the data via the onmessage event handler. The data is stored in the event.data property.

Simple JavaScript Worker exampe

Here is an exampe, a script that displays a count number which runs continuously in a worker file. The script is stored in the "workers_ex.js" file and used it into a webpage.

Code in workers_ex.js

var ic =0;

function timedCount(){
 ic++;
 postMessage(ic);
 setTimeout('timedCount()', 500);
}

timedCount();

Code in webpage

<h4>Example JavaScript Worker</h4>
<blockquote>Count numbers: <b id='resp'></b></blockquote>
<button id='bt_startw'>Start Worker</button> - 
<button id='bt_stopw'>Stop Worker</button> - 

<script>
var wrk; //to store Worker object
var resp = document.getElementById('resp');

function startWorker(){
 if(window.Worker){
 //if wrk undefined or false, defines it
 if(!wrk) wrk = new Worker('javascript/worker_ex.js');

 //adds data in #resp when message from worker
 wrk.addEventListener('message', (ev)=>{
 resp.innerHTML = ev.data;
 });
 }
}

function stopWorker(){ 
 wrk.terminate();
 wrk = false;
}

//click event on Start /Stop Worker buttons
document.getElementById('bt_startw').addEventListener('click', startWorker);
document.getElementById('bt_stopw').addEventListener('click', stopWorker);
</script>

Receiving data in the worker file

The page script cand send data to the worker script with the postMessage() method.

var wrk = new Worker('worker.js');
wrk.postMessage('Data sent to worker');

The worker receives data via the onmessage event, in the event.data property.
addEventListener('message', (ev)=>{
 var data = ev.data;
}

You can send any type of data with postMessage(): string, number, array, object, boolean.


- Example, when the user types some text into an input field, data is send as a string to an worker that sends back an object with the string in reverse order, and the number of characters.

Code in worker_ex.js

//when data is received from webpage
addEventListener('message', (ev)=>{
 var str = ev.data;

 //object with data to send with postMessage()
 var re ={s:str.split('').reverse().join(''), n:str.length};
 postMessage(re);
}

Code in webpage

<h4>Example data to worker</h4>
<p>Type some text in this field:</p>
Text: <input type='text' id='inp1'/>
<blockquote id='resp'>Here it displays the text reversed, and number of characters.</blockquote>

<script>
var resp = document.getElementById('resp');

//defines Worker object if the browser supports it
var wrk = (window.Worker) ? new Worker('javascript/worker_ex.js') :false;

//if wrk defined
if(wrk){
 //on keyup event
 document.getElementById('inp1').addEventListener('keyup', (ev)=>{
 wrk.postMessage(ev.target.value); //post data to worker
 });

 //gets data from worker
 wrk.addEventListener('message', (ew)=>{
 if(ew.data.n) resp.innerHTML ='Reversed text: '+ ew.data.s +'<br>Nr. characters: '+ ew.data.n;
 });
}
</script>

Normally web workers are not used for such simple scripts, but for more CPU intensive tasks, in applications like games, WebSockets, and repetitive ajax requests.
To debug the JS code in worker file, you can use console.log() method in that file.


Terminate Worker

When a web worker object is created, it will continue to listen for messages (even after the external script is finished) until it is terminated.
To terminate a web worker from the main page, and free browser/computer resources, use the terminate() method.

workerObj.terminate()

In the worker thread, workers may close themselves by calling their own close() method.
//worker file
// code to run..

if(some condition) close();

Importing scripts in worker file

With the importScripts() function you can import one or more external scripts in the worker file.

importScripts('foo.js'); //imports foo.js
importScripts('foo.js', 'bar.js'); //imports two scripts
importScripts('//example.com/hello.js'); //imports scripts from other domain
The browser loads and executes each listed script. Any global objects from each script may then be used by the worker.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which HTML5 tag is indicated to be used as container for menu with navigation links in Web site?
<section> <nav> <article>
<nav><ul>
 <li><a href="http://coursesweb.net/css/" title="CSS Course">CSS Course</a></li>
 <li><a href="http://www.marplo.net/jocuri/" title="Flash Games">Flash Games</a></li>
</ul></nav>
Which CSS property shifts an item horizontally to the left or right of where it was?
text-align clear float
.some_class {
  width: 30%;
  float: left;
}
Click on the Math object method which returns x, rounded downwards to the nearest integer.
Math.ceil(x) Math.abs(x) Math.floor(x)
var num = 12.34567;
num = Math.floor(num);
alert(num);       // 12
Indicate the PHP function which returns the number of characters in string.
mb_strlen() count() stristr()
$str = "string with utf-8 chars åèö";
$nrchr = mb_strlen($str);
echo $nrchr;        // 30
JavaScript Worker

Last accessed pages

  1. Get and Modify content of an Iframe (32086)
  2. Keep data in form fields after submitting the form (12347)
  3. JpGraph - Create Graph, Charts, Plots in PHP (3801)
  4. PuzzleImg - Script to Create Image Puzzle Game (9399)
  5. Working with HTML attributes in PHP (13487)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (207)
  2. Read Excel file data in PHP - PhpExcelReader (74)
  3. The Four Agreements (68)
  4. PHP Unzipper - Extract Zip, Rar Archives (66)
  5. Get and Modify content of an Iframe (52)