Sistemas y Tecnologías Web: Servidor

Master de II. ULL. 1er cuatrimestre


Organization ULL-MII-SYTWS-2122   Classroom ULL-MII-SYTWS-2122   Campus Virtual SYTWS   Chat Chat   Profesor Casiano

Table of Contents

Web Worker Examples

Web Worker Examples

Simple web-worker

Ejemplo de uso de Web Workers.

File index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">

    <title>Web Workers basic example</title>

    <link rel="stylesheet" href="style.css">
    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>

  <body>

    <div class="controls" tabindex="0">

    <form>
      <div>
        <label for="number1">Multiply number 1: </label>
        <input type="text" id="number1" value="0">
      </div>
      <div>
        <label for="number2">Multiply number 2: </label>
        <input type="text" id="number2" value="0">
      </div>
      <div>
        <input type="button" value="Compute" id="click">
      </div>
    </form>

    <p class="result">Result: 0</p>

    </div>
  </body>
  <script src="main.js"></script>
</html>

File main.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let first = document.querySelector('#number1');
let second = document.querySelector('#number2');
let compute = document.querySelector('#click');

let result = document.querySelector('.result');

if (window.Worker) { //check if Browser supports the Worker api.
  // Requires script name as input
  let myWorker = new Worker("worker.js");

  compute.onclick = function() {
    console.log('Message posted to worker '+first.value+', '+second.value);
    myWorker.postMessage([Number(first.value), Number(second.value)]); //sending message as array to the worker
  };

  myWorker.onmessage = function(e) {
    console.log(e);
    result.textContent = e.data;
    console.log('Message received from worker '+e.data);
  };
}

File worker.js

1
2
3
4
5
6
7
onmessage = function(e) {
  console.log('Message received from main script: '+e.data);
  let workerResult = 'Result: ' + (e.data[0] * e.data[1]);
  console.log('Posting message back to main script: "'+workerResult+'"');
  postMessage(workerResult);
}

RUN it

Puede encontrar los códigos de ejemplo en este repo:

Ejemplo: Fibonacci

  • Repo de ejemplo fibonacci-worker
    • ~/local/src/uai/uai2015
    • ~/campus-virtual/1920/sytws1920/apuntes/tema1-introduccion/practicas/p2-t1-c3-file-system/event-loop/fibonacci-worker

Can you create a web worker inside a web worker? Answer: yes!

Tutorial by Chinenye Onuegbu: Code examples for JSDay Canarias 2019

Parallel.js

Referencias

Comment with GitHub Utterances