John David

John David

1559198041

JavaScript Web Workers: A Beginner’s Guide

Learn how web workers help with web app performance, and get started by building a basic JavaScript web worker.

In 2019, the web ecosystem has evolved to the point where the browser is an execution environment for applications built on JavaScript. This is reflected in the speed with which the industry comes up with new frameworks, paradigms, module loaders and bundlers, dependency managers, build tools, and package managers year after year.

When JavaScript was conceived in the early days of the internet, the direction of internet development was not clear. Due to the constant, rapid change in the industry and ecosystem, the need for the backward-compatibility of browsers and web standards, the evolution of JavaScript became a constant stream of patches, hacks and afterthoughts.

Today’s mobile devices normally come with 8+ CPU cores, or 12+ GPU cores. Desktop and server CPUs have up to 16 cores, 32 threads, or more.

In this environment, having a dominant programming or scripting environment that is single-threaded is a bottleneck.

JavaScript Is Single-threaded

This means that by design, JavaScript engines — originally browsers — have one main thread of execution, and, to put it simply, process or function B cannot be executed until process or function A is finished. A web page’s UI is unresponsive to any other JavaScript processing while it is occupied with executing something — this is known as DOM blocking.

This is terribly inefficient, especially compared to other languages.

If we go to JS Bin and run this code in the browser’s JavaScript console:

//noprotect
i = 0;
while (i < 60000) {
  console.log("The number is " + i);
  i++;
}


… the whole jsbin.com website will become unresponsive until the browser counts — and logs — to 60,000.

We won’t be able to interact with anything on the page, because the browser is busy.

Now, this is a relatively undemanding computing process, and today’s web apps often involve much more demanding tasks.

We need to be able to compute things in the background while the user seamlessly interacts with the page.

Web Workers

The W3C published a first draft of the web workers standard in 2009. The full specification can be found on the Web Hypertext Application Technology Working Group website — or WHATWG — a web standards body alternative to W3C.

Web workers is an asynchronous system, or protocol, for web pages to execute tasks in the background, independently from the main thread and website UI. It is an isolated environment that is insulated from the window object, the document object, direct internet access and is best suited for long-running or demanding computational tasks.

Apart from web workers — a system dedicated to multithreading — there are other ways to achieve asnychronous processing in JavaScript, such as asynchronous Ajax calls, and event loop.

To demonstrate this, we will go back to JS Bin and try this snippet:

console.log("A");
setTimeout(function(){console.log("B");},2000);
console.log("C");
setTimeout(function(){console.log("D");},0);
console.log("E");
setTimeout(function(){console.log("F");},1000);


When we run this, our log sequence is A, C, E, D, F, B. The browser first schedules operations without the timeout, as they come, and then it executes the setTimeout() functions in the order of their respective specified delays. However, this asynchronicity should not be automatically conflated with multithreading. Depending on the host machine, this can often be just a single-thread stack of the calls in the order we explained.

Web Workers & Multithreading

As Mozilla’s JavaScript reference website explains, web workers are a “means for web content to run scripts in background threads.”

We use them in the following way: we check for the availability of the Worker() constructor in the browser, and if it is available, we instantiate a worker object, with the script URL as the argument. This script will be executed on a separate thread.

The script must be served from the same host or domain for security reasons, and that is also the reason that web workers won’t work if we open the file locally with a file:// scheme.

if (typeof(Worker) !== "undefined") {  
    worker = new Worker("worker.js");
}            


Now we define this code in the worker.js file:

i = 0;
while (i < 200000) {
    postMessage("Web Worker Counter: " + i);
    i++;
}


The Separation of Threads

An important thing to note here is the separation of the window and document scope of execution in the main browser window thread, and the worker scope.

In order to make use of the worker thread, these two scopes need to be able to communicate. To achieve this, we use the postMessage() function within the worker.js file — to send messages to the main browser thread — and the worker.onmessage listener in the main thread to listen to worker messages.

We can also send messages from the main browser thread to the worker thread or function. The only difference is that we reverse things, and call worker.postMessage() on the main thread, and onmessage on the worker thread. To quote Mozilla’s developer reference:

Notice that onmessage and postMessage() need to be hung off the Worker object when used in the main script thread, but not when used in the worker. This is because, inside the worker, the worker is effectively the global scope.
We can use the terminate() method in the same way, to end our worker’s execution.

With all this in mind, we come to this example:

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Web Workers Example</title>

    <style type="text/css">
    body {padding-top:28px;}
    .output-cont {margin-left:12%; margin-top:28px;}

    .output-cont h3 {width:200px; height:100%;}
    .output-cont button {padding:4px 8px; font-size:1.1rem; font-family:sans-serif;  }

    </style>
</head>

<body>

<div class="output-cont"><button onclick="testWorker()">start worker</button><h3 id="workerOutput"></h3><button onclick="terminateWorker()">terminate worker</button></div>
<br/>
<div class="output-cont"><button onclick="testMainThread()">start blocking thread</button><h3 id="mainThreadOutput"></h3></div>
<br/>
<div class="output-cont"><button onclick="alert('browser responsive!')">test browser responsiveness</button></div>

  <script>

    var worker;

    function testWorker() {
        if (typeof(Worker) !== "undefined") {
            if (typeof(worker) == "undefined") {
                worker = new Worker("worker.js");
            }
            worker.onmessage = function(event) {
                document.getElementById("workerOutput").innerHTML = event.data;
            };
        } else {
            document.getElementById("workerOutput").innerHTML = "Web Workers are not supported in your browser";
        }
    }
    function terminateWorker() { 
        worker.terminate();
        worker = undefined;
    }

    function testMainThread() {
        for (var i = 0; i < 200000; i++) { 
            document.getElementById("mainThreadOutput").innerHTML = "Main Thread Counter: " + i;

        }
    }

  </script>

</body>

</html>


and worker.js:

i = 0;
while (i < 200000) {
    postMessage("Web Worker Counter: " + i);
    i++;
}


This gives us the opportunity to test out the effects of main-thread execution on page behavior and performance versus the web worker’s effects.

In this tutorial, we used http-server to serve the files locally.

Now we can see that the worker thread does not block the interactivity of the main browser process, and looping through 200,000 numbers does not affect the main thread. The numbers in the #workerOutput element are updated on every iteration.

The blocking thread, or main thread, when engaged in a loop, blocks all interactivity (we have set the number of iterations to 200,000 here, but it will be even more obvious if we increase it to 2,000,000).

One more thing that points us to a blocked main thread is that the worker process updates the page on every iteration, and the loop in the main thread (the one defined in index.html) only updates the #mainThreadOutput element on the last iteration.

This is because the browser is too consumed with counting (for loop) to be able to redraw the DOM, so it does it only once its business with the for loop is fully done (at the end of the loop).

Conclusion

In this article, we introduced web workers, a technology that helps the web industry keep up with more and more demanding web apps. This is done by providing a way for web apps to leverage multi-processor and multi-threaded devices by bestowing some multi-threaded superpowers to JavaScript.

Web workers turn the mobile and desktop browser environments into application platforms, providing them with a strict execution environment. This strictness may force us to provide for the copying of objects between multiple threads, and to plan our applications with these constraints in mind.

Do you have any tips regarding web workers, and the web as a programming platform? Let us know in the comments!

#javascript #web-development

What is GEEK

Buddha Community

JavaScript Web Workers: A Beginner’s Guide

Ajay Kapoor

1626321063

JS Development Company India | JavaScript Development Services

PixelCrayons: Our JavaScript web development service offers you a feature-packed & dynamic web application that effectively caters to your business challenges and provide you the best RoI. Our JavaScript web development company works on all major frameworks & libraries like Angular, React, Nodejs, Vue.js, to name a few.

With 15+ years of domain expertise, we have successfully delivered 13800+ projects and have successfully garnered 6800+ happy customers with 97%+ client retention rate.

Looking for professional JavaScript web app development services? We provide custom JavaScript development services applying latest version frameworks and libraries to propel businesses to the next level. Our well-defined and manageable JS development processes are balanced between cost, time and quality along with clear communication.

Our JavaScript development companies offers you strict NDA, 100% money back guarantee and agile/DevOps approach.

#javascript development company #javascript development services #javascript web development #javascript development #javascript web development services #javascript web development company

Sival Alethea

Sival Alethea

1624298400

Learn JavaScript - Full Course for Beginners. DO NOT MISS!!!

This complete 134-part JavaScript tutorial for beginners will teach you everything you need to know to get started with the JavaScript programming language.
⭐️Course Contents⭐️
0:00:00 Introduction
0:01:24 Running JavaScript
0:04:23 Comment Your Code
0:05:56 Declare Variables
0:06:15 Storing Values with the Assignment Operator
0:11:31 Initializing Variables with the Assignment Operator
0:11:58 Uninitialized Variables
0:12:40 Case Sensitivity in Variables
0:14:05 Add Two Numbers
0:14:34 Subtract One Number from Another
0:14:52 Multiply Two Numbers
0:15:12 Dividing Numbers
0:15:30 Increment
0:15:58 Decrement
0:16:22 Decimal Numbers
0:16:48 Multiply Two Decimals
0:17:18 Divide Decimals
0:17:33 Finding a Remainder
0:18:22 Augmented Addition
0:19:22 Augmented Subtraction
0:20:18 Augmented Multiplication
0:20:51 Augmented Division
0:21:19 Declare String Variables
0:22:01 Escaping Literal Quotes
0:23:44 Quoting Strings with Single Quotes
0:25:18 Escape Sequences
0:26:46 Plus Operator
0:27:49 Plus Equals Operator
0:29:01 Constructing Strings with Variables
0:30:14 Appending Variables to Strings
0:31:11 Length of a String
0:32:01 Bracket Notation
0:33:27 Understand String Immutability
0:34:23 Find the Nth Character
0:34:51 Find the Last Character
0:35:48 Find the Nth-to-Last Character
0:36:28 Word Blanks
0:40:44 Arrays
0:41:43 Nest Arrays
0:42:33 Access Array Data
0:43:34 Modify Array Data
0:44:48 Access Multi-Dimensional Arrays
0:46:30 push()
0:47:29 pop()
0:48:33 shift()
0:49:23 unshift()
0:50:36 Shopping List
0:51:41 Write Reusable with Functions
0:53:41 Arguments
0:55:43 Global Scope
0:59:31 Local Scope
1:00:46 Global vs Local Scope in Functions
1:02:40 Return a Value from a Function
1:03:55 Undefined Value returned
1:04:52 Assignment with a Returned Value
1:05:52 Stand in Line
1:08:41 Boolean Values
1:09:24 If Statements
1:11:51 Equality Operator
1:13:18 Strict Equality Operator
1:14:43 Comparing different values
1:15:38 Inequality Operator
1:16:20 Strict Inequality Operator
1:17:05 Greater Than Operator
1:17:39 Greater Than Or Equal To Operator
1:18:09 Less Than Operator
1:18:44 Less Than Or Equal To Operator
1:19:17 And Operator
1:20:41 Or Operator
1:21:37 Else Statements
1:22:27 Else If Statements
1:23:30 Logical Order in If Else Statements
1:24:45 Chaining If Else Statements
1:27:45 Golf Code
1:32:15 Switch Statements
1:35:46 Default Option in Switch Statements
1:37:23 Identical Options in Switch Statements
1:39:20 Replacing If Else Chains with Switch
1:41:11 Returning Boolean Values from Functions
1:42:20 Return Early Pattern for Functions
1:43:38 Counting Cards
1:49:11 Build Objects
1:50:46 Dot Notation
1:51:33 Bracket Notation
1:52:47 Variables
1:53:34 Updating Object Properties
1:54:30 Add New Properties to Object
1:55:19 Delete Properties from Object
1:55:54 Objects for Lookups
1:57:43 Testing Objects for Properties
1:59:15 Manipulating Complex Objects
2:01:00 Nested Objects
2:01:53 Nested Arrays
2:03:06 Record Collection
2:10:15 While Loops
2:11:35 For Loops
2:13:56 Odd Numbers With a For Loop
2:15:28 Count Backwards With a For Loop
2:17:08 Iterate Through an Array with a For Loop
2:19:43 Nesting For Loops
2:22:45 Do…While Loops
2:24:12 Profile Lookup
2:28:18 Random Fractions
2:28:54 Random Whole Numbers
2:30:21 Random Whole Numbers within a Range
2:31:46 parseInt Function
2:32:36 parseInt Function with a Radix
2:33:29 Ternary Operator
2:34:57 Multiple Ternary Operators
2:36:57 var vs let
2:39:02 var vs let scopes
2:41:32 const Keyword
2:43:40 Mutate an Array Declared with const
2:44:52 Prevent Object Mutation
2:47:17 Arrow Functions
2:28:24 Arrow Functions with Parameters
2:49:27 Higher Order Arrow Functions
2:53:04 Default Parameters
2:54:00 Rest Operator
2:55:31 Spread Operator
2:57:18 Destructuring Assignment: Objects
3:00:18 Destructuring Assignment: Nested Objects
3:01:55 Destructuring Assignment: Arrays
3:03:40 Destructuring Assignment with Rest Operator to Reassign Array
3:05:05 Destructuring Assignment to Pass an Object
3:06:39 Template Literals
3:10:43 Simple Fields
3:12:24 Declarative Functions
3:12:56 class Syntax
3:15:11 getters and setters
3:20:25 import vs require
3:22:33 export
3:23:40 * to Import
3:24:50 export default
3:25:26 Import a Default Export
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=PkZNo7MFNFg&list=PLWKjhJtqVAblfum5WiQblKPwIbqYXkDoC&index=4

🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#javascript #learn javascript #learn javascript for beginners #learn javascript - full course for beginners #javascript programming language

Zena  Sporer

Zena Sporer

1594720956

A Beginner’s Guide to … in JavaScript

What is … ?

The ‘…’ or spread operator is a useful tool for syntax in JavaScript. It can be used in:

  • Function calls
  • Arrays/Strings
  • Rest Parameters

Let’s go through how to use it in each of the mentioned uses.

Function Calls

1. ‘new’ object using array

Traditionally, you cannot use the ‘new’ keyword to create an object using an array directly. I’m talking about something like a new Date(array) (a new Date Object). Using an array in the constructor is not valid but with ‘…’ , it becomes possible:

const date = [2020, 0, 1];  // 1 Jan 2020
const dateObj = new Date(...date);

console.log(dateObj);
// VM60:1 Wed Jan 01 2020 00:00:00 GMT-0500 (Eastern Standard Time)

2. ‘apply()’ method

The ‘…’ can be used just like the apply() method in JavaScript.

For example, instead of using apply():

const array = ['a', 'b'];
const elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]

You can use ‘…’ for a more concise syntax like so:

const array = ['a', 'b'];
const elements = [0, 1, 2];
array.push(...elements);
console.info(array); // ["a", "b", 0, 1, 2]

For more details on how _apply()_ works, you can read up at w3schools.com/js/js_function_apply.asp.

#beginners-guide #javascript #web-development #programming

Lowa Alice

Lowa Alice

1624379820

JavaScript Tutorial for Beginners: Learn JavaScript in 1 Hour

Watch this JavaScript tutorial for beginners to learn JavaScript basics in one hour.
avaScript is one of the most popular programming languages in 2019. A lot of people are learning JavaScript to become front-end and/or back-end developers.

I’ve designed this JavaScript tutorial for beginners to learn JavaScript from scratch. We’ll start off by answering the frequently asked questions by beginners about JavaScript and shortly after we’ll set up our development environment and start coding.

Whether you’re a beginner and want to learn to code, or you know any programming language and just want to learn JavaScript for web development, this tutorial helps you learn JavaScript fast.

You don’t need any prior experience with JavaScript or any other programming languages. Just watch this JavaScript tutorial to the end and you’ll be writing JavaScript code in no time.

If you want to become a front-end developer, you have to learn JavaScript. It is the programming language that every front-end developer must know.

You can also use JavaScript on the back-end using Node. Node is a run-time environment for executing JavaScript code outside of a browser. With Node and Express (a popular JavaScript framework), you can build back-end of web and mobile applications.

If you’re looking for a crash course that helps you get started with JavaScript quickly, this course is for you.

⭐️TABLE OF CONTENT ⭐️

00:00 What is JavaScript
04:41 Setting Up the Development Environment
07:52 JavaScript in Browsers
11:41 Separation of Concerns
13:47 JavaScript in Node
16:11 Variables
21:49 Constants
23:35 Primitive Types
26:47 Dynamic Typing
30:06 Objects
35:22 Arrays
39:41 Functions
44:22 Types of Functions

📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=W6NZfCO5SIk&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=2
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#javascript #javascript tutorial #javascript tutorial for beginners #beginners

Abigail betty

Abigail betty

1624226400

What is Bitcoin Cash? - A Beginner’s Guide

Bitcoin Cash was created as a result of a hard fork in the Bitcoin network. The Bitcoin Cash network supports a larger block size than Bitcoin (currently 32mb as opposed to Bitcoin’s 1mb).

Later on, Bitcoin Cash forked into Bitcoin SV due to differences in how to carry on its developments.

That’s Bitcoin Cash in a nutshell. If you want a more detailed review watch the complete video. Here’s what I’ll cover:

0:50 - Bitcoin forks
2:06 - Bitcoin’s block size debate
3:35 - Big blocks camp
4:26 - Small blocks camp
5:16 - Small blocks vs. big blocks arguments
7:05 - How decisions are made in the Bitcoin network
10:14 - Block size debate resolution
11:06 - Bitcoin cash intro
11:28 - BTC vs. BCH
12:13 - Bitcoin Cash (ABC) vs. Bitcoin SV
13:09 - Conclusion
📺 The video in this post was made by 99Bitcoins
The origin of the article: https://www.youtube.com/watch?v=ONhbb4YVRLM
🔺 DISCLAIMER: The article is for information sharing. The content of this video is solely the opinions of the speaker who is not a licensed financial advisor or registered investment advisor. Not investment advice or legal advice.
Cryptocurrency trading is VERY risky. Make sure you understand these risks and that you are responsible for what you do with your money
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#bitcoin #blockchain #bitcoin cash #what is bitcoin cash? - a beginner’s guide #what is bitcoin cash #a beginner’s guide