Does the utilization of setTimeout(function, 100) have an impact on performance?

I have implemented a function that continuously checks if the URL contains any of the navigation hrefs every 100ms. If it finds a match, specific elements are assigned the class active.

Here's the code snippet:

    var checkActive = function(){
        var path = window.location.pathname,
            path = decodeURI(path),
            path = path.replace(/[\/]/, "");

        if ( window.location.pathname.indexOf(path) > -1 ) {
        $('.navigation .nav li a[href*="' + path + '"]').parent().addClass('active');
        $('.navigation .nav li a:not([href*="'+path+'"])').parent().removeClass('active');
    }

    (function loopingFunction() {
        checkActive();
        setTimeout(loopingFunction, 100);
    })();

However, I am concerned about whether checking every 100ms will impact the performance for users with slower PCs?

P.s: The reason I opted for this approach is because I am utilizing pushState, statechange and .load() to update my content dynamically without refreshing the entire page.

Answer №1

There is minimal impact on performance as it is a quick check done 10 times per second. To optimize, you can compare the unparsed value of location.hash with the last used value:

var lastHash = String(location);
var checkActive = function(){
    if (lastHash === String(location)) {
        return;
    }
    // ...do work...
};

However, this method is mainly needed for older browsers. For newer browsers, you can simply utilize the hashchange event and check its support like so:

if (typeof window.onhashchange !== "undefined") {
    // Modern browser, use hashchange event
} else {
    // Older browser, implement a workaround
}

(Apologies, the scope extends beyond just hash fragments.)

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

Conflicting TypeScript enum types: numbers and numbers in NestJS/ExpressJS

Incorporating types into my NestJS server has been a priority. After creating a controller (a route for those who prefer Express), I attempted to define the type for params: public async getAllMessages( @Query('startDate', ValidateDate) start ...

Is there a way to change the color of a number's font based on whether it is preceded by a "+" or "-" sign?

I am currently working on a stocks widget and I have a specific requirement. Whenever there is a change in value in the Change or Changeinpercent columns, I need to dynamically set the font color to red for a decrease (-) or green for an increase (+). Her ...

I am looking to preload a separate webpage prior to the HTML loading in AngularJS

I am looking to implement a feature in my AngularJS app where a different webpage (e.g. google.com) will be loaded based on the response of a REST API before any default HTML content is displayed. I have attempted to make a REST service call within a fact ...

The dropdown submenu in Bootstrap 3 remains persistently open

I'm currently working on creating a submenu dropdown and following this reference link: https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_js_dropdown_events2&stacked=h However, I am facing an issue where all my submenus are always ...

Error: ng-messages syntax issue with the field parameter

Encountering the following error: Syntax Error: Token '{' invalid key at column 2 of the expression [{{field}}.$error] starting at [{field}}.$error]. when attempting to execute the code below (form-field.html) <div class='row form-grou ...

Display a loading indicator or progress bar when creating an Excel file using PHPExcel

I am currently using PHPExcel to create excel files. However, some of the files are quite large and it takes a significant amount of time to generate them. During the file generation process, I would like to display a popup with a progress bar or a waitin ...

React Animation Library With Smooth Initial Render and No Dependency on External Props

I'm currently implementing a Modal component within my app, utilizing Portals. My goal is for the Modal to smoothly fade in when it is rendered and fade out when it is no longer displayed. Upon examining the documentation for react-transition-group, ...

What is the advantage of utilizing AngularJs .constant() over simply declaring a JavaScript const variable?

Currently, I am involved in a project using AngularJS where we have implemented a .constant() provider to define some fundamental details that are utilized throughout the entire project. An example of this would be specifying a cookie name like so: .const ...

Update a particular class following an AJAX POST request in JavaScript

After conducting extensive research, I have come here seeking your assistance with a particular issue: I am using a comment system with multiple forms on the same page (utilizing FOSCommentBundle in Symfony). My goal is to be able to post comments via Aja ...

What's the process for including delivery charges in Stripe transactions?

I am facing an issue with Stripe where I am unable to incorporate delivery fees into my transactions. How can I successfully integrate this feature? let line_items = []; for (let productId of uniqIds) { const quantity = productsIds.filter(id => id == ...

Please provide the date using the Foundation Datepicker tool

Beginner in JavaScript here! I am having an issue with submitting dates selected using the Foundation Datepicker from . I have searched for solutions on StackOverflow like Post form on select with JQuery Datepick, but none seem to work in my case. If a Ja ...

I am facing an issue where using JSON stringify in React Native successfully returns my array, but it is unable to display

Every time I input {alert(JSON.stringify(cart[0]))} in my react-native application, the result displayed is the complete array of objects as shown below: [{ "id": 3, "name": John, . . }] However, when I try {alert(JSON.stringif ...

Trigger the dimming effect on the webpage when HTML5 video starts playing

After using this particular script: <script> myVid=document.getElementById("video1"); myVid.oncanplay=alert("Can start playing video"); </script> http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_av_event_canplay A notification windo ...

What is the method for setting the content-type in an AJAX request for Android browsers?

I am facing an issue with my ajax call to the Rails server. The response from the server varies between HTML and JSON based on the content type. Surprisingly, this works smoothly on iPhone and desktop browsers like Chrome, but I am encountering a problem o ...

Overflow due to cascading style sheets

THE ANSWER TO THIS QUESTION HAS BEEN PROVIDED In regards to this particular div that contains two unordered lists, I am seeking a solution where these lists can be positioned side by side instead of above or below each other. I have attempted various met ...

attempting to transform promise-queue demo for use in a nodejs environment

Looking to adapt the promise-queue from a sample JQuery fiddle to Nodejs due to it meeting my needs. However, I'm running into some issues where my code is throwing an error: "TypeError: dfd.promise is not a function" return dfd.promise(); The g ...

Combining three.js geometry and selecting objects with an octree

I have been utilizing Three.js to showcase a variety of custom geometries in different positions and rotations. These geometries are static and do not change frequently, but users have the ability to manipulate them by adding, deleting, or altering the sha ...

Having difficulty upgrading from BootStrap 3 to BootStrap 4

Need assistance updating from BootStrap 3 to BootStrap 4 on my local server. After trying to update, I ended up with a result that still reflects BootStrap 3. https://i.sstatic.net/Bs9H0.jpg Here's the code snippet I used for linking: <link rel=& ...

I possess a variety of poppers and desire for the opened one to close when another one is opened

Having built a component that generates 6 unique experiences, each with its own popper containing images, I am struggling to figure out how to modify my code so that one popper closes when another is clicked. Here is the current setup: This is the compone ...

The overflow hidden function does not seem to be fully functional on the iPad

Struggling to prevent body scrolling when a modal pop-up appears? I've tried setting the body overflow to hidden when opening the modal and resetting it when closing, which worked fine on desktop browsers. However, mobile devices like iPod/iPhone pose ...