ray an
ray an

Reputation: 1288

converting synchronous code to asynchronous code

I am learning to develop chrome extensions(and at the same time learning javascript as well). I am experimenting with an extension that runs on youtube webpage. The thing is when I scroll, sometimes the webpage kinda feels a little jittery.

So, I started looking for possible reasons. I came across a few good videos including "what the heck is event loop by Philip Roberts" in which he talked about event loop and other related stuff. This made me wonder if it's because of this very reason the webpage feels jittery. The code in the content script is synchronous and I don't have much experience with asynchronous coding in javascript. Concepts like promises, async/await are new to me.

Here is the code in the content script at a very high level.

chrome.storage.sync.get(); // getting some data here
let activateButton = document.createElement("div");
activateButton.id = "activate-ext";
activateButton.addEventListener("click", getData);
  1. there is a call to chrome storage api
  2. some code to render a button(there is a click event listener attached to this button which renders another UI.)
  3. then I added this button to the dom

Now, most of the stuff is happening in the getData callback. When a user clicks on that button. the extension:

  1. retrieve data from the webpage and does some regex matching and then the string values that I want is stored in an array a.
  2. then when I have the array a, I am using a map on it to create another array b
  3. then another operation on all the elements of b to get another array c.
  4. and now finally when I have the array c, I call another function that generates the final UI(using values from the array c)

This is how getData looks like:

function getdata(){
    const regex = /some_regex/g;
    let match = regex.exec(data);
    while (match) {
            a.push(match[index]);
            match = regex.exec(description)
        }
    b = createAnotherArray(a) // this function returns array b 
    c = anotherOperation(b) 
    generateUI(c) // in this function I am rendering the UI
}

Now, all this code is synchronous(apart from the call to chrome storage API and some callbacks) and I believe some of these operations(like regex matching) take time which blocks the event loop.

So what would be the best way to restructure this whole code using promises(async/await) so it does not block the browser from rendering/updating UI. I also saw some loops with async/await and I too have loops in my code too. So, do I need to do that too?

Upvotes: 0

Views: 293

Answers (1)

Ziarno
Ziarno

Reputation: 7572

JavaScript is single-threaded. Event loop included - simply, it's just a queue for tasks put into it. If your JS code is actually causing performance issues doing some stuff asynchronously won't help, since then that code will block the event loop anyway.

Only available option is Web workers.

Upvotes: 1

Related Questions