Iterate through a large JavaScript object using setTimeout

What is the most efficient way to iterate through large object elements without freezing the browser?

I have successfully looped through arrays using setTimeout/setInterval in this manner:

var i = 0;
var l = arr.length;
var interval = window.setInterval(function(){
   var k = 100; // process 100 items on each Timeout
   var element;
   while(k--) {
      if (i == l) {
          return clearInterval(interval);
      }
      element = arr[i++];
      // ... work here ...
   }
}, 100);

But when dealing with very large objects, what other methods can I use?

  • Iterating through keys using for(k in arr) will create one large loop that should be avoided.
  • It's not possible to use .splice() on objects since they are not arrays.

Currently, I resort to creating an array like this

[{k: .., v:...},{k: .., v:...},{k: .., v:...},{k: .., v:...},{k: .., v:...},{k: .., v:...},{k: .., v:...},...]
, but it feels like a wasteful use of space.

Answer №1

Utilizing Object.keys allows for the same logic to be applied with objects.

let index = 0;
let objKeys = Object.keys( myData );
let length = objKeys.length;
let timer = window.setInterval(function(){
   let limit = 100; // process 100 items on each Timeout
   let item;
   while(limit--) {
      if (index == length) {
          return clearInterval(timer);
      }
      item = myData[ objKeys[index++] ];
      // ... operations here ...
   }
}, 100);

If dealing with millions of keys, it is advisable to seek alternative approaches as looping through such a massive dataset may not be efficient. Consider breaking down the data into batches for processing.

This raises the question: Is there a legitimate need for millions of objects to reside in memory simultaneously? This scenario hints at a potential design flaw that warrants addressing.

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

Vue.js numerical input module

My approach involves utilizing Numeral.js: Vue.filter('formatNumber', function (value) { return numeral(value).format('0,0.[000]') }) Vue.component('input-number', { templa ...

I'm trying to create a horizontal list using ng-repeat but something isn't quite right. Can anyone help me figure out

Feeling a bit lost after staring at this code for what seems like an eternity. I'm trying to create a horizontal list of 2 image thumbnails within a modal using Angular's ng-repeat. Here's the HTML snippet: <div class="modal-body"> ...

Checking the security status of a PDF file in the web browser to determine if it

Within my platform, individuals have the ability to upload PDF files for others to access at a later time. In order to accommodate this functionality, I require that these PDFs are not secured or encrypted, and can be easily viewed by any user. To ensure ...

Refreshing JSON data every 10 seconds using SVG/D3

What is the best way to program a D3/json/ajax query that retrieves new data every 10 seconds? Here is my initial attempt at a solution, but I believe it may not be ideal: setInterval(function() { d3.json("http://1.....", function(json) { .... }) ...

Retrieve the data from Mysql database, transform the information inside the link into XML format, and display the final output

UPDATED CODE <?php #header( "Content-Type: application/xml" ); function doLoop($arr = array()) { global $newsStory; foreach( $arr as $r ) { //check if we're dealing with an array (multiple links) if ( is_array($r) === true ) ...

In ReactJS, when you encounter TextField values that are "undefined", it is important to handle them appropriately

I'm a beginner when it comes to ReactJs and Material-UI, so please bear with me if my question seems silly. Currently, I have a file named Main.js which includes the following code snippet: handleChange = (name, event) => { if(event==null) ...

Extract the <img> element from the Angular model property

I'm currently leveraging Angular to display some HTML content: <p class="description" ng-model="listing.Description"></p> When the content is rendered, it includes images within the text, which is acceptable. However, now I aim to ident ...

Techniques for triggering JavaScript on elements that have been dynamically loaded via Ajax

When it comes to ensuring that a certain functionality works both when the document is ready and after an Ajax call, there are some considerations to keep in mind for optimal performance. An approach I found effective involves defining the desired code wi ...

Remove any objects with nil values from an array using filter and flatMap in Swift 4

I am populating a UICollectionView with results retrieved from a query. Occasionally, the records returned do not contain images. I want to exclude these objects completely. How can I avoid displaying results from a JSON query that do not include any imag ...

Avoid causing the newline character to display

var i = 'Hello \n World' console.log(i) /* Output: Hello World */ /* Desired output: Hello \n world */ var j = 'javscr\u0012ipt' console.log(j) /* Output: javscr ipt */ /* Desired output: javscr\u0012ipt */ ...

Tips on building a blog using solely index.html, style.css, and script.js files

Looking for inspiration for blog listing pages? Check out some examples like: HubSpot's marketing blog or iGoMoon's blog. I'm trying to figure out where I should start. Should I begin with the first line of code? Or can I import sample code ...

Changing the data request body in datatables ajax on button click

My goal is to initially fetch data when the page loads and then allow users to apply filters by clicking on them to fetch updated data. The query I am using is a POST request because it requires complex parameters that need to be formatted as JSON for bett ...

JavaScript tool: Verify the presence of both jQuery and jQuery UI

I have been working on developing a Javascript Widget (almost complete), and when integrating it into the first site I encountered some issues. My Widget requires loading multiple libraries (jquery, jquery ui, mustache, ...); this is achieved by injecting ...

Validation check for zip codes that flags errors specifically for certain states

I am working on designing a form that triggers an error message when users enter a specific zip code or range of zip codes. For instance: If someone fills out a form and types in a zip code from Washington state, I would like an error message to appear i ...

Node.js and JavaScript promises are not pausing for the sequelize query to complete

The promise mentioned below should ideally return the customer and blox slot as part of the booking record in the second .then(). However, it seems that addCustomer and addBooking have not been executed yet. When I added await to addBooking or addCustomer ...

Is it possible for a Javascript code to execute multiple tasks upon being inserted into the browser's URL bar?

Is it feasible for JavaScript to simulate a user clicking on a link, triggering a pop-up, automatically clicking a button within the pop-up, and then redirecting the user to a final page once a specific code is copied and pasted into the browser's add ...

Display and conceal elements based on their data attributes

Struggling with toggling the visibility of elements within a div based on select value changes. I tried using data- attributes to target the elements for manipulation, but for some reason, my code isn't working as expected. Here's a simplified ...

A guide on managing Ngb Bootstrap carousel slide with a button in Angular

I encountered a situation like this: I need to implement a Ngb Bootstrap carousel with buttons for Previous and Next to control the slide images. Clicking on the Previous button should display the previous slide image, and clicking on the Next button shou ...

Having trouble with implementing forEach in Google Script

Hey there, I'm having a syntax error in my GoogleScript. This is actually my first script ever, so I'm a bit lost as to why it's not working. The main goal is to extract data from a Google sheet and use it to create labels based on a documen ...

showcase a variety of visualizations using ggplot2 in R by iterating through a for loop and

My goal is to showcase multiple plots simultaneously using ggplot2 in R. Although the original dataset includes over 200 cities, for demonstration purposes, I have generated a random sample dataset: #sample data df <- data.frame( city = c('p ...