Loop through a JSON object using a sequence of setTimeout() functions

After running another function, I have retrieved a JSON object stored in the variable 'json_result'.

My objective is to log each individual JSON part (e.g. json_result[i]) after waiting for 5 seconds.

Here was my initial attempt:

for (let key in json_result) {
setTimeout(() => {
if(json_result.hasOwnProperty(key)) {
    console.log(key + " -> " + JSON.stringify(json_result[key]));
 };
 },5000);
 };

Despite using the 'let' keyword for scoping, it didn't work as expected.

In my second approach, I tried delegating the setTimeout functionality:

for (let key in json_result) {
setTimeout(() => {
if(json_result.hasOwnProperty(key)) {
    delayer(key);
 };
 },5000);
 };

function delayer(i) {
    setTimeout(() => { console.log(i + "->" + JSON.stringify(json_result[i]));}, 5000)};

Can anyone explain why this isn't working and suggest a solution?

Thank you,

Answer №1

This is a solution you may find helpful

const data = {
  "item1": "value1",
  "item2": "value2",
  "item3": "value3"
}


const items = Object.keys(data)
counter = 0;
const displayData = () => {
  console.log(items[counter] + " -> " + JSON.stringify(data[items[counter]]));
  counter++;
  if (counter < items.length) setTimeout(displayData, 5000);
};
displayData();

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

Encountering an issue while attempting to integrate mongoose with vue and receiving an error

Whenever I attempt to import this code, the page throws an error: Uncaught TypeError: Cannot read properties of undefined (reading 'split') import { User } from '@/assets/schemas' export default { name: 'HomeView', mount ...

Following the modifications made to the JSON file using Groovy, the file now includes additional curly brackets and a "content" object within the data

Within my json file, I have the following data: {"globals":{"code":"1111","country_code":"8888","hits":80,"extra_hit":1,"keep_money":true},"time_window":{"from& ...

End event in NodeJS response does not activate

I'm encountering an issue with sending the response data to the client. The response is not being sent and the 'end' event is not triggered. I'm at a loss on how to resolve this issue. My objective is to send the retrieved data from red ...

Transformation of JSON data from Array to Object

I have a JSON data structure that looks like this: { tag: 'new-tag', stream_subjects: [1, 2, 3] } My goal is to transform it into the following format: { tag: 'new-tag', stream_subjects: [ {subject_id: 1}, {subject_id ...

Leverage the power of axios in your React application to retrieve information from an

I have been exploring how to use axios for fetching data from an API (https://reqres.in/) and displaying it in my React application. Previously, I used the fetch method in JavaScript to retrieve data from APIs. Despite trying various resources, I am unsure ...

Error encountered during installation of Grunt Bower

As an AngularJS beginner, I am trying to start a node server with npm start on a project cloned from Bitbucket. However, I encountered an error while doing this. I attempted a few solutions such as unblocking port 22 in the firewall settings and running t ...

Merging an assortment of items based on specific criteria

I have the following TypeScript code snippet: interface Stop { code: string } interface FareZone { name: string; stops: Stop[]; } const outbound: FareZone[] = [{name: 'Zone A', stops: [{ code: 'C00'}] }, {name: 'Zone B ...

Using JavaScript to create a dynamic to-do list that persists on the browser even when refreshed

I created a Javascript Todolist that is functioning well, but I am seeking a way to ensure that my Todo-items persist on the browser even after refreshing until I choose to delete them. Any suggestions or advice on how I can achieve this? ...

Is there a way to execute a javascript function that is located outside of my Angular application without having to import it?

I need to be able to trigger a JavaScript function that is located outside of my Angular app when a button is clicked. Unfortunately, it seems that importing the JavaScript directly into my Angular app isn't feasible for this task. The platform I am ...

Having trouble setting the image source in HTML with Node.js

I am a beginner with nodeJS and I am having trouble setting the src attribute of an img tag in my client side html. My node server is running on port 3000 and everything works fine when I visit http://localhost:3000. Here is the code from my server.js fil ...

Troubleshooting issues with AJAX script and JSON formatted data

Here is my complete script: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/E ...

Creating a dynamic 2D image using HTML5 animation

As a beginner HTML5 developer, I have been exploring ways to create an animated image using multiple jpg files stored in a specific folder on my website. My goal is to design an animation of a rabbit running across the page when a user clicks on a button. ...

Converting a single 10GB zip file into five separate 2GB files with the help of NodeJS

var fs = require('fs'); var archiver = require('archiver'); var output = fs.createWriteStream('./test.zip'); var archive = archiver('zip', { gzip: true, zlib: { level: 9 } // Sets the compression level. }); ...

Tips on toggling the visibility of div elements with JavaScript

In my selection block, I have three categories of elements and associated Divs. The goal is to display the related divs when a category is selected, while keeping them hidden otherwise. Specifically, I want the husband_name and number_pregnancy divs to be ...

Converting to JSON format by utilizing MemoryStream and including line breaks in C#

My objective is to convert C# class data into JSON format using a MemoryStream and DataContractJsonSerializer. MemoryStream stream1 = new MemoryStream(); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person)); ser.WriteObject(stre ...

Icon bar struggling to contain voluminous material card content

I've incorporated Material UI cards into my project and have an icon bar at the bottom of each card. However, the media within the card is overflowing onto the icon bar, causing a layout issue as illustrated in this screenshot: Below is the code snip ...

Establishing the preset values for Material-UI toggle button group

I utilized the Material UI library to implement a button toggle widget for selecting options. Check out my codesandbox project here - https://codesandbox.io/s/50pl0jy3xk The user can interact by choosing a membership type: adult, child, or infant. Option ...

HTML5: Enhancing Video Playback on the iPad with Custom Zoom Controls

I've customized a smaller UIWebView specifically for the iPad, and I've created my own HTML5 controls for the video playback. However, when I try to maximize the video, all I see is a black screen instead of the actual content. The audio still pl ...

Creating dynamic and interactive web pages can be achieved by utilizing either $_POST or $_GET with Modal,

In the snippet below, you'll find the HTML code that pulls an array of 6 objects from a database and displays them in a Bootstrap row successfully. <div class="row products"> <?php while($product = mysqli_fetch_assoc($featured)) ...

Update the displayed locations on Google Maps by fetching and displaying marker data

I am able to retrieve and display information from my MySQL table, but I need assistance with refreshing this data every 5 seconds using my current code. The data being shown is not extensive, just about 5 or 8 markers at a time. Below is the code I curren ...