Home > database >  Create async instances of loops and manage them
Create async instances of loops and manage them

Time:11-10

I am using a chrome extension to activate infinite async instances of loops so they do not conflict with each other.

There is a list of values and one item is being passed to each individual loop. Those loops are executed in the content.js and are being managed by the background.js but they are initialized, started and cancelled from the popup.js.

Now big Question is how do I use best practices to make the management of multiple async loops as easy as possible? Is there any possible way to also cancel these loops in an easy way?

example code:

content.js:

chrome.runtime.onMessage.addListener(
     function(request, sender, sendResponse) {
if(request.message.active){
      console.log("do something");
      dispatch(request.message);
}});


async function dispatch(alternator) {
    if (alternator.active) {
        await new Promise(resolve => setTimeout(resolve, alternator.timeout));
        console.log("do something");
    }
    return;
}

This background.js should have a list of async loops to manage in an array or something easy to manage. The for-loop is consuming too much time and the timeout is causing too much load.

background.js

async function dispatchBackground() {
    while (1) {
        for (let i = 0; i < alternator.length; i  ) {
            if(alternator[i].active){
                chrome.tabs.sendMessage(alternator[i].tab_id, {"message": alternator[i]});
            }
        }
        await new Promise(resolve => setTimeout(resolve, 100));
    }
    return;
}

CodePudding user response:

You should probably use a library.

...but that would be boring!

In the following

  • Related