workers

index.html :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Workers</title>
    <script src="main.js"></script>
</head>
<body>
    1 USD = <span id="currencyRate"></span> INR
</body>
</html>

main.js :

const currencyWorker = new Worker("currency-rate-worker.js");

currencyWorker.postMessage('INR');

currencyWorker.onmessage = (event) =>
{
    console.log("USD to INR rate:", event.data);
    document.getElementById('currencyRate').innerText = event.data;
};

currency-rate-worker.js

const get_usd2inr = async () =>
{
    const url = "https://open.er-api.com/v6/latest/USD";
    try
    {
        const response = await fetch(url);
        const data = await response.json();
        const usd2inr = Number(data.rates.INR.toFixed(2));
        return usd2inr;
    }
    catch (error)
    {
        console.error('Error fetching exchange rate:', error);
        throw error;
    }
}

onmessage = async (e) =>
{
    if (e.data === 'INR')
    {
        postMessage(await get_usd2inr());
    }
};
0
Subscribe to my newsletter

Read articles from Anjanesh Lekshminarayanan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Anjanesh Lekshminarayanan
Anjanesh Lekshminarayanan

I am a web developer from Navi Mumbai working as a consultant for NuSummit (formerly cloudxchange.io). Mainly dealt with LAMP stack, now into Django and trying to learn Laravel and Google Cloud. TensorFlow in the near future. Founder of nerul.in