My page is experiencing delays due to setInterval

Currently, I am delving into the world of Chrome Extension development and am faced with a roadblock in replacing elements on a live chat page. While most of my tasks are running smoothly, the one thing causing issues is the setInterval option that triggers the function every 3 seconds.

The need for setInterval arises from the fact that each time a new chat message appears on the console, it generates a

<td class=".profile-image">New Message</td>
element in the table. To style this element using CSS, I require it to have a specific class attached to it.

However, upon loading the page with all previous messages, there is a delay of 2 seconds before all messages appear, during which the class=".profile-image" element is not present. In order to tackle this issue, I added a setTimeout function to wait for 3 seconds before executing the desired action. The catch here is that this action only occurs once, necessitating a repeat of the process for every new chat message. My attempt to address this involved implementing a setInterval to continuously run the function, but this resulted in significant lag on the entire page.

My ultimate goal is to have the function automatically detect the presence of a new message and add the necessary class without causing any performance hitches.

Thank you for any assistance provided!

var dostuff = function() {
  setTimeout(function() {
    jQuery(".profile-image img").each(function() {
      this.src = this.src.replace('small.jpg', 'large.jpg');
      this.src = this.src.replace('small.png', 'large.png');
      $(".profile-image img").attr("height", "64");
      $(".profile-image img").attr("width", "64");
      $(".profile-image img").attr("class", "pro_img");
    });
  }, 2000);
};

setInterval(dostuff, 3000);

Answer №1

Monitoring the webpage for updates or intercepting the script responsible for adding these images would be a more efficient approach. However, if you must continue polling the page, there are some enhancements you can implement to ensure better performance:

  1. When using a setInterval to poll the page, omit the unnecessary setTimeout inside it as it only shifts the interval.
  2. Optimize the DOM search process as it consumes more resources. Avoid multiple redundant searches by iterating through each image once and making modifications accordingly.
  3. To reduce the number of operations, consider consolidating your CSS rules into a single class instead of applying them individually.
  4. If possible, remove any unnecessary class names from modified elements to prevent reselecting them in subsequent iterations.
  5. Enhance search efficiency by narrowing down the scope. Utilize closer parent elements with unique IDs to limit the DOM traversal (#foo .profile-image img). ID selectors perform better than class selectors due to their direct lookup nature.

Result:

var dostuff = function() {
    $(".profile-image img").each(function() {
        this.src = this.src.replace('small.png', 'large.png');
        $(this).addClass('pro_img') // include height and width rules in the class CSS
             .removeClass('profile-image'); // move necessary styles to .pro_img if not relying on profile-image
    });
};

setInterval(dostuff, 3000);

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

Implementing scrolling functionality within a nested container

I need help with getting a nested container (.widget2) to scroll while still keeping the borders intact. Currently, the inner container is scrolling past the bottom edge of the parent container, and the scrollbar isn't displaying correctly. If you w ...

"Node.js and Webpack - the dynamic duo of

Have you ever wondered why we need to use webpack and npm to install node for JavaScript, when we can simply run JavaScript code directly in our browser? And how exactly do we go about implementing webpack into our project files? ...

Can you identify the HTML table format and suggest effective web scraping methods?

I have been attempting to retrieve data from the following link, http://www.rchsd.org/doctors/index.htm? strt = 0 & ln = & fn = & sp = & grp = & loc = & lng = & gen = , using R but finding it quite challenging. I have observed that the URL remains constan ...

What is the best way to extract the text from a <div> tag and show it in a different div when clicked on using ng click in AngularJS?

When the button is clicked, the text in ng-model=name should be displayed in the <h2> tag. <div ng-model="name">This is a text</div> <button ng-click="getname()">Click</button> <h2>{{name}}</h2> ...

Difficulty in implementing a radio button selection form using Django and Bootstrap styles

Currently, I am facing an issue while trying to develop a form with radio button choices using Django. The website is based on Bootstrap 4 theme and encountering a problem where the buttons disappear upon applying the custom-control-input class. I initial ...

Transition smoothly with a fade-in effect as you scroll through the images, and proceed to

My Objectives: Implement a scrolling feature where images transition to the next one based on scroll movement. Create a cycle of images that automatically progress, with the view transitioning to the bottom section once all images are viewed. Currently f ...

Error: X does not conform to function definition

I'm currently in the process of developing a Vue application that interacts with Spotify's API to search for tracks. However, I've encountered an issue where I receive the following error message: Uncaught (in promise) TypeError: searchTra ...

When adding an object to an array in AngularJS, it seems to trigger updates for

Currently, I am fetching data from a WebAPI and then storing it in an array called products, which is scoped. $scope.products In addition to the products array, I also have another scoped array named selectedFish. $scope.selectedFish = []; My objective ...

What could be causing my custom cursor to malfunction?

I've been attempting to customize the cursor image, but despite following all provided instructions, it's still not working: CSS: body, html { margin: 0px; padding: 0px; border: 1px solid red; cursor: url(images/rsz_red_crosshair.gi ...

When using Ionic, clicking on a Google Maps marker to navigate to another page with NavController can sometimes result in the clicks on the new

Upon successfully displaying the pushed page, I encountered a strange issue where all elements with a (click)='doSomething()' binding stopped working throughout the newly loaded page. Additionally, there was an ion-slides element on the pushed pa ...

Color schemes for items in the Windows store app

I'm having trouble changing the background color of an item in my split application. I've tried using CSS, but nothing seems to work. Here is the template for the item (default style): <div class="itemtemplate" data-win-control="WinJS.Bindin ...

Bringing in Vue from 'vue' allows for the incorporation of 'different' Vue to diverse documents

This issue involves the interaction between Webpack, ES6 import syntax, and Vue. Currently, I am working on a Vuex mutation that is responsible for adding a new key-value pair mykey: [] to an object within the state. To ensure reactivity, I need to use Vu ...

Effectively controlling two distinct Azure resources within one domain name through domain routing

I am currently in the process of deploying a React application on Microsoft Azure that includes a basic content management feature. Essentially, when users visit the website and access static content, the app retrieves HTML code from a database and display ...

Leverage JavaScript to customize the appearance of existing links within an external HTML document

Forgive me for my lack of expertise in Javascript. I will do my best to explain clearly. On my website, I have an external html file for the navigation menu that is loaded with javascript to simplify editing (so I don't need to update nav elements on ...

Run HTML/Angular ng-include with JavaScript

I am developing a small search app using AngularJS. I have an empty div that I want to replace with another div containing ng-include after running a function. The replacement of the div works fine, but ng-include does not load properly. For testing purpo ...

Issue with form submission using getElementById

I am struggling to submit a form that is generated by PHP echo. The getElementById function doesn't seem to be functioning properly. <?php include 'connect.php' ; $sql=mysql_query("SELECT mess_id,receiver,subject ...

The Splitter remains inactive until a peculiar series of actions is taken

Trying to troubleshoot this issue with a library called Split.js, which can be found here: https://github.com/nathancahill/Split.js I've encountered an interesting problem where I have to disable the height CSS property of my container, move the spli ...

What is the reason AJAX does not prevent page from refreshing?

Can anyone offer some guidance on using AJAX in Django? I'm attempting to create a basic form with two inputs and send the data to my Python backend without refreshing the page. Below is the AJAX code I am using: <script type="text/javascript& ...

responsive position absolute to the auto width of position absolute

Here is an example of my CSS code: https://jsfiddle.net/80e4u0dd/ When you hover over the orange box, the a element gets underlined. The orange box needs to stay above the "long text" in the green box, just like it is currently. The issue is that the oran ...

Tool to identify your network location: Local domain and network status checker

Is there a way to determine if a user is accessing our site from within our local network or from the broader internet? For example, imagine someone scans a QR code at our restaurant that leads to a page designed to check whether they are connected locall ...