Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 6599

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 27, 20242024-11-27T08:01:07+00:00 2024-11-27T08:01:07+00:00

Building a Frontend Currency Application with Javascript Multithreading/Web Workers

  • 60k

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! 😀

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

  • Frontend Crypto Application: Footer
  • Frontend Crypto Application: Footer

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 🤟💪🤟💪

frontendjavascriptprogrammingwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.