From 1109132f09d75da9a28b649c7677bb6ce07c40c0 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:45 -0500 Subject: initial commit --- files/es/web/api/worker/index.html | 155 +++++++++++++++++++ files/es/web/api/worker/postmessage/index.html | 206 +++++++++++++++++++++++++ files/es/web/api/worker/terminate/index.html | 107 +++++++++++++ 3 files changed, 468 insertions(+) create mode 100644 files/es/web/api/worker/index.html create mode 100644 files/es/web/api/worker/postmessage/index.html create mode 100644 files/es/web/api/worker/terminate/index.html (limited to 'files/es/web/api/worker') diff --git a/files/es/web/api/worker/index.html b/files/es/web/api/worker/index.html new file mode 100644 index 0000000000..4be8325629 --- /dev/null +++ b/files/es/web/api/worker/index.html @@ -0,0 +1,155 @@ +--- +title: Worker +slug: Web/API/Worker +tags: + - API + - DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web Workers + - Worker + - Workers +translation_of: Web/API/Worker +--- +

{{APIRef("Web Workers API")}}

+ +

The Worker interface of the Web Workers API represents a background task that can be easily created and can send messages back to its creator. Creating a worker is as simple as calling the Worker() constructor and specifying a script to be run in the worker thread.

+ +

Workers may in turn spawn new workers as long as those workers are hosted within the same origin as the parent page (Note: nested workers are currently not implemented in Blink).  In addition workers may use XMLHttpRequest for network I/O, with the stipulation that the responseXML and channel attributes on XMLHttpRequest always return null.

+ +

Not all interfaces and functions are available to the script associated with a Worker.

+ +

In Firefox, if you want to use workers in extensions and would like to have access to js-ctypes, you should use the {{ domxref("ChromeWorker") }} object instead.

+ +

Properties

+ +

Inherits properties from its parent, {{domxref("EventTarget")}}, and implements properties from {{domxref("AbstractWorker")}}.

+ +

Event handlers

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
An {{ domxref("EventListener") }} called whenever an {{domxref("ErrorEvent")}} of type error bubbles through to the worker. This is inherited from {{domxref("AbstractWorker")}}.
+
{{domxref("Worker.onmessage")}}
+
An {{ domxref("EventListener") }} called whenever a {{domxref("MessageEvent")}} of type message bubbles through the worker — i.e. when a message is sent to the parent document from the worker via {{domxref("DedicatedWorkerGlobalScope.postMessage")}}. The message is stored in the event's {{domxref("MessageEvent.data", "data")}} property.
+
+ +

Constructors

+ +
+
{{domxref("Worker.Worker", "Worker()")}}
+
Creates a dedicated web worker that executes the script at the specified URL. Workers can also be constructed using Blobs.
+
+ +

Methods

+ +

Inherits methods from its parent, {{domxref("EventTarget")}}, and implements properties from {{domxref("AbstractWorker")}}.

+ +
+
{{domxref("Worker.postMessage()")}}
+
Sends a message — which can consist of any JavaScript object — to the worker's inner scope.
+
{{domxref("Worker.terminate()")}}
+
Immediately terminates the worker. This does not offer the worker an opportunity to finish its operations; it is simply stopped at once. ServiceWorker instances do not support this method.
+
+ +

Example

+ +

The following code snippet shows creation of a {{domxref("Worker")}} object using the {{domxref("Worker.Worker", "Worker()")}} constructor and usage of the object:

+ +
var myWorker = new Worker("worker.js");
+
+first.onchange = function() {
+  myWorker.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+ +

For a full example, see ourBasic dedicated worker example (run dedicated worker).

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#worker", "Worker")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#worker", "Worker")}}{{Spec2('Web Workers')}}Initial definition.
+ +

Browser compatibility

+ +

Support varies for different types of workers. See each worker type's page for specifics.

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support43.510.010.64
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support4.43.51.0.110.011.55.1{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/es/web/api/worker/postmessage/index.html b/files/es/web/api/worker/postmessage/index.html new file mode 100644 index 0000000000..c47fe400fc --- /dev/null +++ b/files/es/web/api/worker/postmessage/index.html @@ -0,0 +1,206 @@ +--- +title: Worker.postMessage() +slug: Web/API/Worker/postMessage +translation_of: Web/API/Worker/postMessage +--- +

{{APIRef("Web Workers API")}}

+ +

Web Workers API posee un metodo llamado postMessage() el cual envia un mensaje al ambito del worker. Este metodo acepta un parametro, el cual es un dato enviado al worker. El dato puede ser un valor o objeto controlado por el algoritmo strctured clone (incluye referencias ciclicas).

+ +

El Worker puede enviar de vuelta información al hilo que lo genero usando el metodo {{domxref("DedicatedWorkerGlobalScope.postMessage")}}.

+ +

Syntax

+ +
myWorker.postMessage(aMessage, transferList);
+ +

Parameters

+ +
+
aMessage
+
The object to deliver to the worker; this will be in the data field in the event delivered to the {{domxref("DedicatedWorkerGlobalScope.onmessage")}} handler. This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references.
+
transferList {{optional_inline}}
+
An optional array of {{domxref("Transferable")}} objects to transfer ownership of. If the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from and it becomes available only to the worker it was sent to.
+
Only {{domxref("MessagePort")}} and {{domxref("ArrayBuffer")}} objects can be transferred.
+
+ +

Returns

+ +

Void.

+ +

Example

+ +

The following code snippet shows creation of a {{domxref("Worker")}} object using the {{domxref("Worker.Worker", "Worker()")}} constructor. When either of two form inputs (first and second) have their values changed, {{event("change")}} events invoke postMessage() to send the value of both inputs to the current worker.

+ +
var myWorker = new Worker("worker.js");
+
+first.onchange = function() {
+  myWorker.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+
+second.onchange = function() {
+  myWorker.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+
+ +

For a full example, see ourBasic dedicated worker example (run dedicated worker).

+ +
+

Note: postMessage() can only send a single object at once. As seen above, if you want to pass multiple values you can send an array.

+
+ +

Transfer Example

+ +

This example is of a Firefox addon that transfers an ArrayBuffer from the main thread to the ChromeWorker, and then the ChromeWorker trasnfers it back to the main thread.

+ +

Main thread code:

+ +
var myWorker = new ChromeWorker(self.path + 'myWorker.js');
+
+function handleMessageFromWorker(msg) {
+    console.log('incoming message from worker, msg:', msg);
+    switch (msg.data.aTopic) {
+        case 'do_sendMainArrBuff':
+            sendMainArrBuff(msg.data.aBuf)
+            break;
+        default:
+            throw 'no aTopic on incoming message to ChromeWorker';
+    }
+}
+
+myWorker.addEventListener('message', handleMessageFromWorker);
+
+// Ok lets create the buffer and send it
+var arrBuf = new ArrayBuffer(8);
+console.info('arrBuf.byteLength pre transfer:', arrBuf.byteLength);
+
+myWorker.postMessage(
+    {
+        aTopic: 'do_sendWorkerArrBuff',
+        aBuf: arrBuf // The array buffer that we passed to the transferrable section 3 lines below
+    },
+    [
+        arrBuf // The array buffer we created 9 lines above
+    ]
+);
+
+console.info('arrBuf.byteLength post transfer:', arrBuf.byteLength);
+
+ +

Worker code

+ +
self.onmessage = function (msg) {
+    switch (msg.data.aTopic) {
+        case 'do_sendWorkerArrBuff':
+                sendWorkerArrBuff(msg.data.aBuf)
+            break;
+        default:
+            throw 'no aTopic on incoming message to ChromeWorker';
+    }
+}
+
+function sendWorkerArrBuff(aBuf) {
+    console.info('from worker, PRE send back aBuf.byteLength:', aBuf.byteLength);
+
+    self.postMessage({aTopic:'do_sendMainArrBuff', aBuf:aBuf}, [aBuf]);
+
+    console.info('from worker, POST send back aBuf.byteLength:', aBuf.byteLength);
+}
+
+ +

Output logged

+ +
arrBuf.byteLength pre transfer: 8                              bootstrap.js:40
+arrBuf.byteLength post transfer: 0                             bootstrap.js:42
+
+from worker, PRE send back aBuf.byteLength: 8                  myWorker.js:5:2
+
+incoming message from worker, msg: message { ... }             bootstrap.js:20
+got back buf in main thread, aBuf.byteLength: 8                bootstrap.js:12
+
+from worker, POST send back aBuf.byteLength: 0                 myWorker.js:7:2
+ +

We see that byteLength goes to 0 as it is trasnferred. To see a fully working example of this Firefox demo addon see here: GitHub :: ChromeWorker - demo-transfer-arraybuffer

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-worker-postmessage", "Worker.postMessage()")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#dom-worker-postmessage", "Worker.postMessage()")}}{{Spec2('Web Workers')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0 [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0 [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Internet Explorer does not support {{domxref("Transferable")}} objects.

+ +

See also

+ + diff --git a/files/es/web/api/worker/terminate/index.html b/files/es/web/api/worker/terminate/index.html new file mode 100644 index 0000000000..d557989f25 --- /dev/null +++ b/files/es/web/api/worker/terminate/index.html @@ -0,0 +1,107 @@ +--- +title: Worker.terminate() +slug: Web/API/Worker/terminate +translation_of: Web/API/Worker/terminate +--- +

{{APIRef("Web Workers API")}}

+ +

El método terminate() de la interfaz {{domxref("Worker")}} termina inmediatamente el {{domxref("Worker")}}. Esto no ofrece la oportunidad de finalizar las operaciones que estuviera realizando el worker, termina la ejecución por completo.

+ +

Sintaxis

+ +
myWorker.terminate();
+ +

Parámetros

+ +

Ninguno.

+ +

Retorna

+ +

Nada.

+ +

Ejemplo

+ +

El siguiente extracto de código muestra la creación de un objeto {{domxref("Worker")}} usando el constructor de  {{domxref("Worker.Worker", "Worker()")}} y éste es inmediatamente terminado.

+ +
var myWorker = new Worker('worker.js');
+
+myWorker.terminate();
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('HTML WHATWG', "#dom-worker-terminate", "Worker.postMessage()")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#dom-worker-terminate", "Worker.postMessage()")}}{{Spec2('Web Workers')}}Definición inicial.
+ +

Compatibilidad de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Soporte básico43.510.010.64
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Soporte básico4.43.51.0.110.011.55.1
+
+ +

Mirar también

+ +

La interfaz {{domxref("Worker")}} a la que pertenece.

-- cgit v1.2.3-54-g00ecf