Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reliably detect if the script is executing in a web worker [duplicate]

I am currently writing a little library in JavaScript to help me delegate to a web-worker some heavy computation .

For some reasons (mainly for the ability to debug in the UI thread and then run the same code in a worker) I'd like to detect if the script is currently running in a worker or in the UI thread.

I'm not a seasoned JavaScript developper and I would like to ensure that the following function will reliably detect if I'm in a worker or not :

function testenv() {
    try{
        if (importScripts) {
            postMessage("I think I'm in a worker actually.");
        }
    } catch (e) {
        if (e instanceof ReferenceError) {
            console.log("I'm the UI thread.");
        } else {
            throw e;
        }
    }
}

So, does it ?

like image 775
thomas Avatar asked Oct 28 '11 15:10

thomas


People also ask

How do I know if WebWorker is running?

Show activity on this post. You should have the web worker post messages about events, like when it is finished work, this way the parent can listen to these messages/events and know when work has completed. The web worker can even post progress events, this is all up to you to build though, it does not come included.

Which of the following code is used to check the web worker object is exists or not if the web worker object is not exists it will create a new web worker?

Method 1: Using the typeof operator The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”.

Where should you place JavaScript code to run in the context of a web worker?

You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the window object.


1 Answers

Quite late to the game on this one, but here's the best, most bulletproofy way I could come up with:

// run this in global scope of window or worker. since window.self = window, we're ok
if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
    // huzzah! a worker!
} else {
    // I'm a window... sad trombone.
}
like image 85
borbulon Avatar answered Oct 12 '22 02:10

borbulon