IE displaying "slow script" alert due to Knockout malfunction

Within my grid of observables and computed observables, the first row serves as a multiplier for all subsequent rows. Users can modify this percentage rate and Knockout automatically updates all relevant values accordingly. Additionally, I require a textbox where users can input a new percentage rate to be applied uniformly across the entire grid.

The initial binding and single rate update functionality are functioning correctly.

An issue arises when attempting to loop through the view model after a value is entered in the textbox. The script encounters a JavaScript warning due to the repetitive nature of updating each percentage rate within the grid columns (which represent monthly values) only 12 times.

I experimented with using the throttle extender, but it did not resolve the problem. Any suggestions?

Update: Though uncertain if it will provide a solution, here is some additional code

$("#NewRate").change(function (e) {
    var newRate = parseFloat($(this).val());
    for (var i = 0; i < 12; i++) {
        viewModel.resourceCategory.monthAmounts[i].amount(newRate);
    }
});

function ConvertToDate(jsonDateString) {
    var re = /-?\d+/;
    var m = re.exec(jsonDateString);
    return new Date(parseInt(m[0]));
}

function MonthAmount(amount, dateKey) {
    var self = this;
    self.amount = ko.observable(amount).extend({ throttle: 1 }); //using the throttle to avoid "long running script" warning in IE
    self.dateKey = ConvertToDate(dateKey);
    self.monthIndex = self.dateKey.getMonth();
}

function ResourceCategory(name, monthAmounts) {
    var self = this;
    self.name = name;

    self.monthAmounts = ko.utils.arrayMap(monthAmounts, function (monthAmount) {
        return new MonthAmount(monthAmount.Amount, monthAmount.DateKey);
    });

    self.totalAmount = ko.computed(function () {
        var sum = 0;
        for (var i = 0; i < self.monthAmounts.length; i++) {
            sum += parseFloat(self.monthAmounts[i].amount());
        }
        return sum.toFixed(2);
    }).extend({ throttle: 1 }); //using the throttle to avoid "long running script" warning in IE

    self.averageAmount = ko.computed(function () {
        return (self.totalAmount() / self.monthAmounts.length).toFixed(2);
    }).extend({ throttle: 1 }); //using the throttle to avoid "long running script" warning in IE

}
function ResourceCategoriesMonthTotal(monthIndex, resourceCategories) {
    var self = this;
    self.monthIndex = monthIndex;
    self.dateKey = new Date(new Date().getFullYear(), monthIndex, 1);
    self.amount = ko.computed(function () {
        var val = 0;
        for (var i = 0; i < resourceCategories.length; i++) {
            val += parseFloat(resourceCategories[i].monthAmounts[self.monthIndex].amount());
        }
        return (val).toFixed(2);
    }).extend({ throttle: 1 }); //using the throttle to avoid "long running script" warning in IE
}

self.resourceCategoriesMonthTotals = new Array();
for (var monthIndex = 0; monthIndex < 12; monthIndex++) {
    self.resourceCategoriesMonthTotals.push(new ResourceCategoriesMonthTotal(monthIndex, self.resourceCategories));
}

self.resourceCategoriesTotal = ko.computed(function () {
    var val = 0;
    for (var i = 0; i < self.resourceCategoriesMonthTotals.length; i++) {
        val += parseFloat(self.resourceCategoriesMonthTotals[i].amount());
    }
    return (val / self.resourceCategoriesMonthTotals.length).toFixed(2);
}).extend({ throttle: 1 }); //using the throttle to avoid "long running script" warning in IE

Answer №1

It seems like the issue arises when you are iterating through the view model to update each of the percentage rates accordingly.

To tackle this problem in Internet Explorer, one workaround could be to let the browser take control by incorporating a timeout(0) function call. Following the timeout delay, proceed with the next iteration of the loop and repeat this process.

In my experience, I have only employed these timeouts if I have detected that the user is using an IE browser. Otherwise, they are not necessary.

Answer №2

Unfortunately, the issue seems to be related to a specific code snippet on my webpage:

<div data-bind="text: ko.toJSON($root)"></div>

Once I removed this code, I no longer experienced the “slow running script” notification.

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

input value does not change when the "keyup" event is triggered

I'm encountering an issue with the code below. The code is for a simple To Do app using Javascript. I followed a tutorial step by step, but my app isn't functioning as expected. When I press the enter key, the input value should be added to the l ...

Creating a repository of essential functions in AngularJSDiscover the steps to set up a

I am looking to create a set of reusable functions in AngularJS for CRUD operations that can be used across multiple entities in my project. I have already set up a factory using $resource for server communication, which looks like this: Model File: var ...

"The Django querydict receives extra empty brackets '[]' when using jQuery ajax post to append items to a list in the app

Currently, I am tackling a project in Django where I am utilizing Jquery's ajax method to send a post request. The csrftoken is obtained from the browser's cookie using JavaScript. $.ajax({ type : 'POST', beforeSend: funct ...

What is the best practice for adding one string to the end of another?

So, is this the best way to concatenate strings in JavaScript? var str = 'Hello'; str += ' World'; While most languages allow for this method of string concatenation, some consider it less efficient. Many programming languages offer a ...

Uncover each image individually

I have a task in React where I am displaying a list of images using the map method, and I want to reveal each image one by one after a delay. The images I am working with can be seen here and I need them to be revealed sequentially. The following code sni ...

Uncovering the User's Browser Specifically for UC-Mini and Opera-Mini

I'm in need of a script that can identify if the user's browser is uc-mini or opera-mini. These particular browsers do not support the "transition" feature. Therefore, when this specific browser is detected, I would like to deactivate the "trans ...

Update the object with fresh data once the XML data is transformed into JSON format

I am currently converting XML attributes into JSON format. Below is the complete function that I will explain step by step: request.execute('[someSP].[spSomeSP]', function(err, dataset) { if (err) { reject(err); } ...

Reactjs encountering issues with CSS loading correctly

Currently, I am working with reactjs and utilizing the Nextjs framework. All my "css, js, images" are stored in the "public" folder and have been included in "_app.js". However, whenever I attempt to load the "Main page" in a browser, the page does not d ...

Intersection Observer API is not compatible with the functionality of the navigation bar

Having trouble with the Intersection Observer API. Attempting to use it to show a nav-bar with a white background fixed to the viewport once it scrolls out of view. Initially tested using console.log('visible') successfully to determine visibili ...

Illuminate the current page

I have been working on a website with around 20 pages that all have a side navigation bar. To make it easier to manage, I decided to centralize the links in a JavaScript (JS) file and include it on each HTML page. This way, any changes can be made quickly ...

What is the method for displaying an array in JavaScript?

When a user clicks the value 3 input box, three input boxes will appear where they can enter values. However, when trying to submit the array, no elements are printed and an error message "Element is not defined" appears. var arr = [0]; function get_va ...

How can we display or conceal text indicating the age of a patient based on the value returned from selectedPatient.age in a React application?

Hello, I am looking to dynamically display the age in years on the screen based on the value retrieved from selectedPatient.age, toggling between visible and hidden states. import React, { useContext } from 'react'; import { useHistory } from &ap ...

Storing account information in a .env file can be a more secure option compared to storing it in a client

Working on a basic nodejs application using express for file processing operations. Planning to package the final app with pkg. I need to implement a login system and one time account creation. The app will launch a browser tab running a vuejs UI app. Cons ...

Troubleshooting jsPDF problem with multi-page content in React and HTML: Converting HTML to PDF

I need to convert HTML content in my React application into a PDF file. My current approach involves taking an HTML container and executing the following code snippet: await htmlToImage .toPng(node) .then((dataUrl) => { ...

Translate data from two "contact form 7" date fields into JavaScript/jQuery to display the date range between them

NEW UPDATE: I was able to get it working, but the code is a bit messy. If anyone can help me clean it up, I would greatly appreciate it. <div class="column one-fourth" id="date-start">[date* date-start date-format:dd/mm/yy min:today+1days placeholde ...

Is there a way for me to personalize the background of the mui-material datagrid header?

I am looking to update the background design of Mui Datagrid from this image to this image However, I am encountering an issue where the background color does not fully cover the header. I have attempted using "cellClassName:" in the columns but it has n ...

Sending a $.ajax post request transforming into a get

Struggling to understand the behavior of my jquery ajax request, I've hit a roadblock. function newContact() { $.ajax({ type: 'POST', contentType: 'application/json', // url: ...

Encountering a 500 (Internal Server Error) while trying to insert data into the database through ajax

In the HTML code, I have a basic AJAX function that is triggered by a button press. The goal is to have the PHP script being called insert the JavaScript variable sent into a database. var myval = 'testuser'; // generated by PHP $.a ...

Adding information to an HTML table using JQuery

Is there a way to incorporate JSON data into an HTML table? The JSON data follows this format: https://i.stack.imgur.com/lzdZg.png This is the desired HTML table structure: <table class="table table-bordered table-hover "> ...

What is causing the initial activation of the <button> within a form?

Within my <form>, I have included 2 submit buttons. The first button looks like this: <button class="regular" id="geocodesubmit" style="height:40px;">Set Location</button> The second button looks like this: <button type="submit" ...