DEV Community

Cover image for Building a Frontend Currency Application with Javascript Multithreading/Web Workers
Renan Ferro
Renan Ferro

Posted on • Updated on

Building a Frontend Currency Application with Javascript Multithreading/Web Workers

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 and Chart.js.

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

Image description


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

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

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:

const myWorker = new Worker('fileName.js');
Enter fullscreen mode Exit fullscreen mode

To say what needs to be done:

myWorker.addEventListener('message', (event) => {
    const data = event.data;
    console.log(`My data is: ${data}`);
});
Enter fullscreen mode Exit fullscreen mode

Send message to the Web Worker

myWorker.postMessage('bitcoin');
Enter fullscreen mode Exit fullscreen mode

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!


CSS


JavaScript:

Noww, let's see the wonderful JavaScript code:

File: workerBitcoinToDolar.js

Code

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);
}
Enter fullscreen mode Exit fullscreen mode

File: workerDolar.js

Code

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);
}

Enter fullscreen mode Exit fullscreen mode

File: script.js

Code

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);
});
Enter fullscreen mode Exit fullscreen mode

File: insertCotation.js

Code

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;

Enter fullscreen mode Exit fullscreen mode

Live demo:

You can see the live demo here: Live demo


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 🀟πŸ’ͺ🀟πŸ’ͺ

Top comments (0)