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

"Assigning an array as a value to an object key when detecting duplicates in a

Let's assume the table I'm iterating through looks like this: https://i.stack.imgur.com/HAPrJ.png I want to convert each unique value in the second column into an object, where one of the keys will hold all values from corresponding rows. Here& ...

What is the best way to utilize regex to replace two elements simultaneously?

I am facing a challenge with manipulating a string of characters by adding span tags to highlight specific words and change their color. While I have successfully implemented the changes for one pattern using regex, I'm struggling to do the same for a ...

XMLHttpRequest problem: receiving status code 0 from both local and live server

I'm struggling to make this XMLHttpRequest work correctly. This is my first time using AJAX, so I'm not sure if I've formatted everything properly. I've searched all over the internet and found similar information and examples, but cert ...

Expanding list - Using individual toggles to expand and collapse multiple list items

I stumbled upon an interesting jquery script that allows for a collapsible sub menu within a list. After implementing this code: $('.menu-item-has-children').prepend('<a id="fa-menu" href="#"><i class="fa fa-plus"></i>< ...

"Utilizing jQuery to integrate an Ajax-powered Gauge using Google Visualization API

I need help creating a dynamic dashboard gauge that updates using ajax. The code snippet below shows what I have so far, but I'm struggling with updating the gauge itself. Any advice or suggestions on how to achieve this? google.load('v ...

Update the text input field from a different webpage

I am working with two PHP pages, let's call them page1.php and page2.php. On page1.php, there is a textbox with a default value of 0, while on page2.php, there is a button. I have these two pages open in different tabs in a browser. My goal is to have ...

Undefined variable when initializing with ng-init

As a newcomer to AngularJS (and JavaScript in general), I'm currently facing an issue that I could use some help with. Below is the HTML template I am using: <ion-view view-title="Playlists"> <ion-content> <ion-list> ...

Error in Vue.js and Socket.io - the server response cannot contain the wildcard '*' when the request has its credentials mode set to 'include'

I'm currently working on creating a chat app using Vue and Socket IO. Here's the error I'm encountering. This is my Node server code. And this is my Vue app code. My Node server and Vue app are separate entities. How can I resolve this i ...

Issue with package: Unable to locate the module specified as './artifacts/index.win32-ia32-msvc.node'

I am encountering an issue while using Parcel for the first time. When I execute npx parcel .\app\index.html, I receive the following error: Error: Module not found './artifacts/index.win32-ia32-msvc.node' Require stack: - C:\Users ...

GraphQL is not capable of fetching data directly from a mysql database

Trying to incorporate GraphQL with MySQL in a Node.js Express server has been my recent challenge. Unfortunately, every time I execute my query, an error surfaces. Here is the specific error message: { "errors": [ { "message&quo ...

Error in React Typescript Order Form when recalculating on change

When creating an order form with React TypeScript, users can input the quantity, unit price, and select whether the item is taxable. In this simplified example, only 1 or 2 items can be added, but in the final version, users will be able to add 10-15 item ...

The Angular Table row mysteriously vanishes once it has been edited

Utilizing ng-repeat within a table to dynamically generate content brings about the option to interact with and manage the table contents such as edit and delete. A challenge arises when editing and saving a row causes it to disappear. Attempts were made ...

How to display an unordered list horizontally in HTML

I'm working on a screen that has filters displayed vertically, but I want to align them horizontally and have the filter options arranged in two columns. I've tried using CSS properties like spacing, clear, and display block, but the checkboxes/l ...

What is the best way to add a constant value to all objects within an array without having to iterate through each one

Is there a more concise way to add a fixed value to each object in an array without using a loop in JavaScript? Programming Language used: JavaScript Example Array: "cars": [ { "name":"Ford", "models":"Fiesta" }, { "name":"BMW", "models":"X1" }, ...

Utilizing Dropzone for file uploads in Node.js, Express, and Angular

I'm running into a bit of trouble trying to get the file recognized on the server side with node.js. Especially when trying to access request data, such as req.files or req.body If anyone has any advice, here are some code snippets: HTML: <form ...

Troubleshooting AJAX Problems in ASP.NET and C#

I am currently working on implementing a WebMethod call in my C# code behind using AJAX. I have a Bootstrap Modal that should be displayed when a linkbutton is clicked, triggering the execution of the WebMethod through AJAX to populate a table in the modal ...

When utilizing a prisma query with a callback function, it appears that try/catch blocks are being overlooked in Node.js

After referencing error handling methods from the prisma documentation, I encountered an issue with my code: try { prisma.daRevisionare.create({ data: { "idTweet": tweet.id, "testo": testotweet, url } }).then((dati) => { bo ...

Sending a Thunk to the store using Typescript

Within my primary store.ts file, the following code is present: const store = createStore( rootReducer, composeWithDevTools(applyMiddleware(thunk)) ); store.dispatch(fetchUser()); Upon initial rendering, an action is dispatched to fetchUser in ord ...

How come React-Native isn't displaying successfully retrieved data using Axios?

I recently installed axios using the command below: npm i axios After writing the code below, I encountered an issue where React-Native doesn't display any data or throw any errors: import React, {useState, useEffect} from 'react'; import a ...

Tips on recycling JavaScript files for a node.js API

I'm currently using a collection of JS files for a node.js server-side API. Here are the files: CommonHandler.js Lib1.js Lib2.js Lib3.js Now, I want to reuse these JS files within an ASP.NET application. What's the best way to bundle these f ...