What is the best approach for writing an asynchronous function while utilizing $rootScope.broadcast within a continuous loop?

At least 10 times a second, I have a function that is called. Each time, there are approximately 100 records with variations in LastSeenTime and ReadCount. In this simulation scenario, I understand the behavior; however, in real-time, the number of records in an array can range from 100 to 1000 and they may or may not be identical. It is essential for me to add all unique records to tagStore, which will then be displayed in the UI.

$scope.$on('getReadTags', function (event, tags) {

        if (($scope.tagStore == null || $scope.tagStore.length == 0) && tags.length != 0) {
            $scope.tagStore = tags;
        }
        else {
            for (var i = 0; i < tags.length; i++) {
                var notFound = true;

                for (var j = 0; j < $scope.tagStore.length; j++) {
                    if (tags[i].TagID == $scope.tagStore[j].TagID) {
                        $scope.tagStore[j].ReadCount += tags[i].ReadCount;
                        $scope.tagStore[j].LastSeenTime = tags[i].LastSeenTime;
                        $scope.tagStore[j].DiscoveryTime = tags[i].DiscoveryTime;
                        notFound = false;
                        break;
                    }
                }
                if (!notFound) {
                    $scope.tagStore.push(tags[i]);
                }
            }
        }
        $scope.$apply();
    });

Upon running this code, my browser becomes unresponsive, and I've noticed a significant spike in CPU and RAM usage. To address this issue, I require this method to only be invoked after the completion of another method.

Answer №1

Running multiple digest cycles consecutively can significantly increase CPU and memory usage, causing the browser to hang.

To optimize this process, consider using $applyAsync instead of $scope.$apply(); to consolidate multiple updates into a single $digest cycle. This approach is recommended in the documentation (bold area):

$applyAsync([exp]); Schedule the invocation of $apply to occur at a later time. The actual time difference varies across browsers, but is typically around ~10 milliseconds.

This can be used to queue up multiple expressions which need to be evaluated in the same digest.

The loop

for (var j = 0; j < $scope.tagStore.length; j++) {
can be optimized as it iterates through the entire list of tags for each tag insertion or update. Consider implementing the following code snippet instead:

var tagsMap;

$scope.$on('getReadTags', function (event, tags) {  
    if (($scope.tagStore == null || $scope.tagStore.length == 0) && tags.length != 0) {
        $scope.tagStore = tags;
        tagsMap = tags.reduce(function(obj, item) {
            obj[item.TagID] = item; // create a map of all tags
        }, {});
    } else {
        for (var i = 0; i < tags.length; i++) {
            if(tagsMap[tags[i].TagID]) { // if tag exists in the map, update the tag
                tagsMap[tags[i].TagID].ReadCount += tags[i].ReadCount;
                tagsMap[tags[i].TagID].LastSeenTime = tags[i].LastSeenTime;
                tagsMap[tags[i].TagID].DiscoveryTime = tags[i].DiscoveryTime;
            } else { // if tag doesn't exist, push it into the scope, and add it to the tagsMap
                $scope.tagStore.push(tags[i]);
                tagsMap[tags[i].TagID] = tags[i];
            }
        }
    }
    $scope.$applyAsync();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

unleashing the magic of AJAX: a guide to extracting

In my Symfony project, I am attempting to retrieve the content of an AJAX request in order to check the data using dump(). The purpose is to process this data and perform a SQL query. However, when I use dump() in my controller, there doesn't appear t ...

A jQuery component with built-in event triggers

Here's an example that illustrates the concept: a widget needs to utilize its own method as a callback: $.widget("custom.mywidget", { _create: function() { this.invoke("mymodule", "myaction", {arg: this.options.value}, this.parseData); ...

Organize array by year and month groupings

I'm trying to organize an array of events by year and month. Here is a sample of my data: const events = [ { name: "event 1", year: 2021, month: 1, }, { name: "event 2", year: 2021, month: 9, }, { ...

Generate an HTML dropdown menu based on the item selected from the autocomplete input field

I have a PHP page that searches the database and returns JSON results to an autocomplete input field: https://i.sstatic.net/PPFgR.png When I display the response from the PHP file (as shown above), it looks like this: { "success": true, "results ...

I encounter a black screen issue while attempting to rotate a three.js cube

How can I rotate a cube around all three axes (x, y, z) using the code snippet provided below? ` <html> <head> <title>CM20219 – Coursework 2 – WebGL</title> <meta charset="utf-8"> < ...

React function failing to utilize the latest state

I'm facing an issue with my handleKeyUp function where it doesn't seem to recognize the updated state value for playingTrackInd. Even though I update the state using setPlayingTrackInd, the function always reads playingTrackInd as -1. It's p ...

Steps for setting up node-openalpr on a Windows 10 system

While attempting to install npm i node-openalpr, an error is occurring: When using request for node-pre-gyp https download, I encounter a node-pre-gyp warning and error message. The package.json for node-openalpr is not node-pre-gyp ready, as certain pr ...

Imitate a HTTP request

Currently, I am working on developing a front-end application using Angular (although not crucial to this question). I have a service set up that currently supplies hard-coded JSON data. import { Injectable } from '@angular/core'; import { Obser ...

Using JQuery to manipulate `this`, its children, its siblings, and more

Can anyone help me determine the most effective way to send data from a get request to a specific div? My challenge is to send it only to a div that is related to the one triggering the action. For example, when I click on the message_tab, I want to send t ...

Utilizing JSON format, handling special characters, and storing data in a database

My friend approached me with a question and although I wanted to offer immediate help, I realized that seeking advice from others may provide better solutions. Situation: Imagine there is a Form that includes a RichText feature: DHTMLX RichText (). This R ...

Monitor modifications to an <input type="text"> element as its value is updated dynamically through JQuery from the server side

I am struggling with detecting when the value of an input field changes after it has been set by clicking a button. I have tried various events but can't seem to find the right one. <!DOCTYPE html> <html> <head> <script src=" ...

What sets xhr.response apart from xhr.responseText in XMLHttpRequest?

Is there any difference between the values returned by xhr.response and xhr.responseText in a 'GET' request? ...

Is it possible to generate distance between 2 elements without utilizing padding or margin?

In my React Native project, I'm currently working with 2 inline buttons - the search and add buttons: https://i.stack.imgur.com/tKZrf.png I'm looking to add some spacing between these buttons without impacting their alignment with the left and ...

Attaching a callback function to a directive using a template tag in Angular

I am having trouble binding a callback to a component using a template. The template includes an instance of another directive, but for some reason it is not working as expected. I am calling the directive from a modal, and I'm not sure if that could ...

Sending an array object from Ajax to Django Framework

AJAX Script Explanation: Let's consider the variable arry1D contains values [0,1,2,3,4] $.ajax({ url: "{% url 'form_post' %}", type: "POST", data: { arry1D: arry1D, 'csrfmiddlewaretoken': tk }, ...

The 401 error code does not provide a JSON response

Here is an example of using Phalcon to create an API: $response = new Response(); $response->setStatusCode( 401, 'Unauthorized' ); $response->setContentType( 'application/json', 'UTF-8' ); $response->setJsonContent( ...

Encountering ReferenceError when attempting to declare a variable in TypeScript from an external file because it is not defined

Below is the typescript file in question: module someModule { declare var servicePort: string; export class someClass{ constructor(){ servicePort = servicePort || ""; //ERROR= 'ReferenceError: servicePort is not defined' } I also attempted t ...

issues with the functionality of bootstrap modal

I'm currently working on a project where I need to set up a modal popup using bootstrap. The website I'm working on is organized by departments, so the only part of the code that I have control over is the main body of the site. I have included t ...

What steps can be taken to stop 'type-hacking'?

Imagine owning a popular social media platform and wanting to integrate an iframe for user signups through third-party sites, similar to Facebook's 'like this' iframes. However, you are concerned about the security risks associated with ifra ...

Modify the color of a div element in React when it is clicked on

My goal is to change the color of each div individually when clicked. However, I am facing an issue where all divs change color at once when only one is clicked. I need help in modifying my code to achieve the desired behavior. Below is the current implem ...