If there is a setTimeout, the sequence of the output will vary

Using a recursive function, I implemented the code to log the tree structure into console.log. To introduce delays during processing, I included setTimeout in the code. However, adding setTimeout resulted in a different output order during processing, with varying delay times.

The purpose of this code is:

Upon finding a child node after searching for the first category title, the code recursively searches for the second category title and then inquires about the children value. This process continues for subsequent categories. Adding setTimeout causes all categories to be processed one after the other rather than simultaneously.

What could be causing this unexpected behavior?

            var time = 0;
            function searchTree(v, t){

                $(v).each(function(i,k){
                    setTimeout(function(){
                        if (t == 'clone'){
                            console.log(k.sCategoryTitle);
                            if (k.children){
                                searchTree(k.children,'clone');
                            }
                        }
                    }, time = time + 100);
                });
            }

View sample code: http://jsfiddle.net/uahg5qd9/3/

Answer №1

To make your function synchronous, you can try the following code. I have opted to remove the loop and replace it with another synchronous function in order to achieve synchronization.

var time = 100;
function searchTree(v, t){
    var i=0;
    function retrieveData(){
        if(i<v.length){
            let k = v[i];    
            if (t == 'clone'){
                console.log(k.sCategoryTitle);
                if (k.children){
                    setTimeout(function(){
                        time = time + 100;
                        searchTree(k.children,'clone');
                    },time);
                }else{
                    i++;
                    retrieveData();
                }
            }else{
                i++;
                retrieveData();
            }
        }else{
            i++;
            retrieveData();
        }
    }
    retrieveData();
}

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

When working with Next.js Components, be aware that using a return statement in a forbidden context can lead to

Whenever I try to add a new component to my Next.js project, I encounter an error that displays the following: `./components/GridMember.js Error: error: Return statement is not allowed here | 6 | return (test); | ^^^^^^^^^^^^^^^^^^^^^^^^^ Caused ...

Guide on determining if the value in a JSON object is a string or an array in Node.js

Running a Node.js application, I encountered the following JSON array structure. First JSON object: var json1= { bookmarkname: 'My Health Circles', bookmarkurl: 'http://localhost:3000/', bookmark_system_category: [ '22&apos ...

How to Transfer Information Between Two React Components

I recently started learning React and I'm not sure how to approach this task. Basically, I have a list of cars and when the user clicks on each car, it should display detailed information about that specific car in a full-page slide. This is my curr ...

Transform React JSX component to ES5 with the help of babel

I have been working on transpiling a JSX React Component to a version that is compatible with ES5. To achieve this, I installed babel using npm at the root of my project directory. { "name": "example", "version": "1. ...

Guide on attaching an event to every dynamically created element in JavaScript

I'm currently generating 'li' elements dynamically using a loop and running into issues when it comes to assigning events to each generated element. My goal is to assign an onclick event to every li element that is created. Check out the co ...

The functionality to rename a label by clicking on an image button is currently malfunctioning

There seems to be an issue with this code where the label name is not changing as expected when clicking the image button. I have noticed that upon closer inspection, the label does change momentarily but then reverts back to its original value immediatel ...

Arranging the picture pieces in various positions

I have recently combined three logo images into a single PNG format file to reduce the number of server requests and improve loading speed. To position the entire image, I can use absolute attributes. For example: div.absolute { position: absolute; t ...

Utilizing ng-repeat, filter, and the uib-popup-datepicker to refine and display specific data within a table column

I'm currently facing a common scenario in my Angular application where I need to filter items from an ng-repeat using an HTML5 input of type 'date' or Angular-UI-Bootstrap's 'uib-popup-datepicker'. Despite extensive research, ...

AngularJS $scope variable is not defined during page load

Experiencing difficulties retrieving service data to include in the variable's scope. Below is my controller code: 'use strict'; var app = angular.module('ezcms2App.controllers', []); app.controller('NoticiaCtrl', [&apo ...

jQuery validation fails to function properly in the absence of errors

I am struggling to understand why my code is not working. There are no error messages in the console. Does the property name in the rule inside validation refer to the id or name of the input form? The library has been correctly included in a general HTML ...

Unable to handle JQuery POST to PHP in success function

I am struggling with a jQuery post function that is supposed to call a PHP script in order to retrieve a value from the database. Although I can see in Firebug that the PHP file is being called and returning a 200 OK status, the success function in my JS ...

Deletion of an element with Reactjs upon clicking

A photo gallery consists of a collection of photos with corresponding delete buttons. Below is the HTML snippet for a gallery containing two images: <div> <div class="image"> <img src="URL1"> <button class="remove">X</ ...

Ensuring input validity and blocking changes if not compliant with AngularJS patterns

I am looking to create an input field that only accepts the values 1, 2, or 3. To achieve this, I am working on a directive that will prevent any changes to the model if it doesn't match these specific values. For example, if the value is 1 and I tr ...

Ways to unlock all the information windows in Google Maps

Is it possible to automatically display all info windows on the map when it is first opened, eliminating the need for users to click on markers? In other words, I would like all info windows for all markers to be shown by default when the map is opened. ...

Issue with React Router version 6: displaying an empty page

I am currently grappling with implementing react-router for my react applications. However, I am encountering issues with the routing part as it consistently displays a blank page. Below are snippets of the code from the involved files: index.js import R ...

Guide on validating an input field of type=date by checking for empty input or if it doesn't match a specified regex pattern, and showing corresponding error messages

I've spent days attempting to create a function that validates whether the input type=Date is both filled out and formatted correctly. The criteria I'm looking for are as follows: If the field is left empty, show an error message: "* is require ...

Error occurred when trying to import an external module using an invalid hook call

I am creating a package named "Formcomponent" using React and React Bootstrap. This code is from index.tsx /** * Renders a component for a form. */ import React from "react"; import Form from "react-bootstrap/Form"; /** * List of props * @returns */ ...

How to Handle CRUD Errors in NodeJS using Mongoose and Return a Custom Response to the Client

Setup NodeJS 10 MongoDB Client side app : Angular 9 About In my NodeJS application, I have a controller and service that work together to create an entity and return a promise. Here's how it looks: Controller async create(@Body() entityData: an ...

Can you show me how to use Yahoo UI (JS) to simulate a click on a specific point (x, y) within an

Can someone help me with simulating a mouse down at point (X, Y) in the client area of an HTML Object using YUI? I checked the documentation here, but I'm still unclear on how to do it. ...

Connecting event logic to Bootstrap 5 dropdown clicks: A quick guide

Is there a way to add an "onclick" event to a Bootstrap 5 dropdown in order to execute application logic based on the selected dropdown item? The Bootstrap docs cover events for when the dropdown is opened and closed, but there doesn't seem to be a s ...