Building a Frontend Currency Application with Javascript Multithreading/Web Workers
Tags: javascript, frontend, webdev, programming
Published: 2023-08-06 17:49:58

Hi, how are you?!

Today I would like to talk about an interesting topic!

Have you ever seen someone talking about **Single-Threaded** or **Multithreading** in JavaScript?!

And you think **"What is this, MY LORD?!"**

This already happened to me a few times until I went after understanding a little more about it! And with that I'd like to share with you what little I learned!

Soo let's do it!
___
## Application Setup

We'll create it with: **HTML**, **CSS**, **JavaScript**, **Web Workers**, [Bootstrap v5](https://getbootstrap.com/) and [Chart.js](https://www.chartjs.org/).

Below you can see how our application will look in the final result::

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i9tet8luziqehwk42qdm.png)
___

## A small and important overview

By default, JavaScript is **Synchronous**, where the **Event Loop** executes the tasks that are in the **Call Stack** line by line! And for that it has the help of the **Task Queue** because some functions may take time to be executed (Like a function with a setInterval()) and with the **Task Queue** we avoid that the code breaks and that makes the code **Asynchronous**.
 
- Threads and MultiThreads, let's talk a bit about it:

Generally, a program or process follows a flow of control, which is executed sequentially step by step through its single flow of control. Threads allow us to have more control flows in our applications!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uk8dnaiq8p2grz2bgkpm.png)

Our application would work as if it had parts of the code running in parallel on our system.

Threads give us the advantage of executing more than one execution at the same time in the same application environment because one thread is independent of the other.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kv8p41grr9fvljioh80f.png)

Bringing all this explanation to our case study, we can have multiple requests to the Crypto API happening at the same time without crashing our application!

> Threads is a very extensive subject, it involves some other concepts such as parallelism among others, but it is very useful and relevant knowledge to have! As in the article we focus more on building the application, I recommend an additional study on the subject, because here we will just give a little read over it! :D

Now, let's see a bit about **Web Workers** and after that build our Frontend Crypto Application!
____

## Web Workers

Workers is very useful because with it we can work with multi threads!

With it we create an object through the Worker() constructor that will execute a proper file. With it, the code inserted in the file will be executed in the created worker Thread.

Then the Threads created from these Workers will be executed in a Thread separated from the window!

Enabling our application not to crash for example, because it is in a separate "queue"!

### How to create/use:

Basically, when we work with it we'll use the structure bellow:

#### Create:

```javascript
const myWorker = new Worker('fileName.js');
```

#### To say what needs to be done:
```javascript
myWorker.addEventListener('message', (event) => {
    const data = event.data;
    console.log(`My data is: ${data}`);
});
```

#### Send message to the Web Worker
```javascript
myWorker.postMessage('bitcoin');
```

Now we know a little about *Web Workers** and how to use it. So let's make our application! 😁😋
___

## Let's build the Application

For the article not to be too long, I will provide the HTML and CSS through the links only without pasting the code, but any questions feel free to leave a comment and we will solve it together

Below you can find the our application separated with modules, like: `HTML`, `CSS`, `JavaScript`.

### HTML
#### File link: [Frontend Crypto Application!](https://stackblitz.com/edit/web-platform-aaousr?file=index.html)
___

### CSS

- [Frontend Crypto Application: Footer](https://stackblitz.com/edit/web-platform-aaousr?file=styles%2Fheader.css)
- [Frontend Crypto Application: Footer](https://stackblitz.com/edit/web-platform-aaousr?file=styles%2Ffooter.css)

___

### JavaScript:

Noww, let's see the wonderful *JavaScript* code:

#### File: [workerBitcoinToDolar.js](https://stackblitz.com/edit/web-platform-aaousr?file=scripts%2Fworkers%2FworkerBitcoinToDolar.js)

#### Code
```javascript
addEventListener('message', (event) => {
  //Invoque de function to conect with API
  conectAPI();

  //Invoque API to update graphic and values
  setInterval(() => conectAPI(), 5000);
});

async function conectAPI() {
  const conectFetchApi = await fetch(
    'https://economia.awesomeapi.com.br/last/BTC-USD'
  );

  const conectApiResponsePayload = await conectFetchApi.json();

  //Post message to the worker
  postMessage(conectApiResponsePayload.BTCUSD);
}
```
___
#### File: [workerDolar.js] (https://stackblitz.com/edit/web-platform-aaousr?file=scripts%2Fworkers%2FworkerDolar.js)

#### Code
```javascript
addEventListener('message', (event) => {
  //Invoque de function to conect with API
  conectAPI();

  //Invoque API to update graphic and values
  setInterval(() => conectAPI(), 5000);
});

async function conectAPI() {
  const conectFetchApi = await fetch(
    'https://economia.awesomeapi.com.br/last/USD-BRL'
  );

  const conectApiResponsePayload = await conectFetchApi.json();

  //Post message to the worker
  postMessage(conectApiResponsePayload.USDBRL);
}

```
___
#### File: [script.js](https://stackblitz.com/edit/web-platform-aaousr?file=scripts%2Fscripts.js)

#### Code
```javascript
import selecionaCotacao from './insertCotation.js';

// Block: Workers Declaratation
let workerDolar = new Worker('./scripts/workers/workerDolar.js');
let workerBitcoinToDolar = new Worker(
  './scripts/workers/workerBitcoinToDolar.js'
);

// Block: Generic/Reusable Functions
function generateTime() {
  let data = new Date();
  return data.getHours() + ':' + data.getMinutes() + ':' + data.getSeconds();
}

function adicionaDados(grafico, legenda, dados) {
  grafico.data.labels.push(legenda);
  grafico.data.datasets.forEach((dataset) => {
    dataset.data.push(dados);
  });
  grafico.update();
}

// Block: Select/Create Chart.js Graphics
const dolarRealGraphic = document.getElementById('dolarRealGraphic');
const graficoIene = document.getElementById('dolarCanadenseGraphic');

const graphicForShowDolarRealComparation = new Chart(dolarRealGraphic, {
  type: 'line',
  data: {
    labels: [],
    datasets: [
      {
        label: 'Dólar',
        data: [],
        borderWidth: 1,
      },
    ],
  },
});

const graficoParaIene = new Chart(graficoIene, {
  type: 'line',
  data: {
    labels: [],
    datasets: [
      {
        label: 'Bitcoin',
        data: [],
        borderWidth: 1,
      },
    ],
  },
});

// Block: Web Workers Structure
workerDolar.postMessage('usd');
workerDolar.addEventListener('message', (event) => {
  let tempo = generateTime();
  let valor = event.data.ask;
  selecionaCotacao('dolar', valor);
  adicionaDados(graphicForShowDolarRealComparation, tempo, valor);
});

workerBitcoinToDolar.postMessage('bitcoin');
workerBitcoinToDolar.addEventListener('message', (event) => {
  let tempo = generateTime();
  let valor = event.data.ask;
  adicionaDados(graficoParaIene, tempo, valor);
  selecionaCotacao('bitcoin', valor);
});
```
___
#### File: [insertCotation.js](https://stackblitz.com/edit/web-platform-aaousr?file=scripts%2FinsertCotation.js)

#### Code
```javascript
const listElement = document.querySelectorAll('[data-lista]');

function selecionaCotacao(name, value) {
  listElement.forEach((listaEscolhida) => {
    if (listaEscolhida.id === name) {
      insertQuotationOnChart(listaEscolhida, name, value);
    }
  });
}

function insertQuotationOnChart(listElement, name, value) {
  listElement.innerHTML = '';

  const wordVariations = {
    dolar: 'Dollars',
    bitcoin: 'Bitcoins',
  };

  for (let multiplicator = 1; multiplicator <= 10000; multiplicator *= 10) {
    const creteLiListElement = document.createElement('li');

    creteLiListElement.innerHTML = `${multiplicator} ${
      multiplicator === 1 ? name : wordVariations[name]
    }: ${wordVariations[name] === 'Dollars' ? 'R$' : 'USD: '}${(
      value * multiplicator
    ).toFixed(2)}`;

    listElement.appendChild(creteLiListElement);
  }
}

export default selecionaCotacao;

```
___
## Live demo:

You can see the live demo here: [Live demo](https://stackblitz.com/edit/web-platform-aaousr?file=index.html)

{% embed https://stackblitz.com/edit/web-platform-aaousr?file=scripts%2Fscripts.js %}
___
That's all guys! With that animation we can turn our websites more nice turning the user experience nice!

Feel free to fork and make your changes, improvements and anything you want 😄.

Hope this makes you feel a bit more comfortable with JavaScript, Threads and Web workers!

Feel free to reach out to me if you have any questions!

and obviously I hope you enjoyed it 🤟💪🤟💪