What causes setInterval to create an endless loop when used inside a while loop in JavaScript?

I attempted to initiate a delayed "one" call or a "one or two?" question, but instead of working as expected, the function continued running indefinitely. Surprisingly, everything worked perfectly fine without using setInterval.

quester2()
function quester2() {
  for (i = 0; i <= finalCount; i++) {
    let K = Math.ceil(Math.random() * 2);
    if (K == 1) {
      setInterval(function () { console.log("one"); }, 1000);
      finalCount += 1;
      allIterations += 1;
      setInterval(function () { console.log("one or two?"); }, 1000);
    } else {
      setInterval(function () { console.log("one or two?"); }, 1000);
      allIterations += 1;
    }
  }
  console.log(finalCount);
  console.log(i);
}

Answer №1

It's important to note that there is no infinite loop occurring in your code; rather, it may simply be taking longer to complete certain iterations compared to past executions. The issue could be related to the increase of the finalCount variable within the condition of the for loop.

The appearance of an infinite loop may stem from running a high number of setIntervals without clearing them. By closely monitoring your console, you'll notice two immediate outputs for the last log statements before seeing repeated occurrences of "one" and "one or two?" shortly after.

quester2()

0
1
one or two?

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 iterating through it, a sorted array in Javascript mutates the window object, but not in any

I am working with Python Django to create a view that returns JSON data to a template. In this template, I initialize a global JavaScript variable like so: <script type="text/javascript"> coordinates = {{ coordinates | safe}} </script> Th ...

AJAX request stops functioning once the page is reloaded

As a beginner in JavaScript, I am facing an issue with my AJAX call. I have set up the call to process a back-end function when a button is clicked and expect to receive a response once the function is completed. However, whenever I refresh the page whil ...

Conceal a column within a nested HTML table

I am facing a challenge with a nested table column structure: My goal is to hide specific columns based on their index within the table. Can someone explain the concept behind achieving this? I am unsure of how to get started on this task. <table clas ...

Working on asynchronous processing of Highland stream fragments

My current setup involves utilizing highland.js to process a file using a stream and extract content between specific delimiters. Additionally, I am incorporating async.js to perform a sequence of http requests. I am seeking a way to pass the output x fro ...

Java - RESTful API endpoint that serves images when available and JSON data when images are not available

I am currently working on incorporating a mobile front-end using the Ionic Framework along with the $cordovaFileTransfer plugin. My focus is on fetching and uploading a person's Profile Photo. Uploading the photo is functioning properly, but I am enco ...

Having trouble with the updateOne() method in MongoDB - it's not updating my document nor displaying any errors. What could be the issue?

I'm currently facing an issue where I am attempting to update a user's document in the database with a value obtained from a calculator. However, despite not encountering any errors, the document does not seem to be updating and the page just con ...

Placing a group of input fields and a button based on the data-id attribute of the element

I have a form that appears when a button is clicked, and the save button saves input values into an object. Is there a more efficient way to write this function if I need to create 9 more buttons with different data-id attributes (e.g. data-id="2" and so ...

Exploring the power of VueJs through chaining actions and promises

Within my component, I have two actions set to trigger upon mounting. These actions individually fetch data from the backend and require calling mutations. The issue arises when the second mutation is dependent on the result of the first call. It's cr ...

The JQuery chosen dropdown experiences a visual issue when placed inside a scrollbar, appearing to be "cut

Good day, I've been using the jQuery "chosen" plugin for a dropdown menu, but I encountered an issue with it being located in a scrollable area. The problem is that the dropdown items are getting cut off by the outer div element. I have provided a si ...

The Material UI Rating Component is malfunctioning and showing an incorrect value

I'm currently working on a component loop that takes in async data. Everything is rendering properly except for the first component, where the Rating component isn't displaying its value correctly (it just shows 0 stars). Here's the code: & ...

Incorrect Reactjs installation technique

When I try to run create-react-app on my Windows PC, only dependencies are being installed with no folders other than node_modules. Even when using Yarn, I haven't been able to progress further. Please assist and thank you in advance for any help. Thi ...

What methods can be used to initiate form error handling in React/Javascript?

I am currently utilizing Material-UI Google Autocomplete, which can be found at https://material-ui.com/components/autocomplete/#google-maps-place, in order to prompt users to provide their address. https://i.stack.imgur.com/nsBpE.png My primary inquiry ...

Attempting to transform HTML code received from the server into an image, but encountering an error while using ReactJS

This app is designed to automate the process of creating social media posts. I have a template for the vertical "Cablgram" stored in the backend, and when I make a request, it returns the HTML code for that template. However, I encounter an error when tryi ...

Creating a concise TypeScript declaration file for an established JavaScript library

I'm interested in utilizing the neat-csv library, however, I have encountered an issue with it not having a typescript definition file available. Various blogs suggest creating a basic definition file as a starting point: declare var neatCsv: any; M ...

tips for navigating through an AngularJS $resource instance

I am facing a frustrating issue that I need assistance with. The problem arises when I try to extract specific data from each element of the stock data fetched by my controller from Yahoo Stocks. Although the data is stored in $scope.stocks and can be disp ...

Using Ajax to invoke a C# webmethod

I'm trying to call a webmethod defined in this specific class <%@ WebService Language="C#" Class="emt7anReyady.myService" %> using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Linq; usi ...

Using JavaScript variables within the value section of a JSON is a common requirement for developers

var averageTemperature = req.params.rating; var destinationName = req.params.name; var query = { "results.name": destinationName }; var updateQuery = { $set: { "results.$.rating": averageTemperature } }; mach.update(query, updateQuery, function(err, res ...

The outcome of the JQuery function did not meet the anticipated result

Here is the code I am using: $("p").css("background-color", "yellow"); alert( $("p").css("background-color")); The alert is showing undefined instead of the expected color value. I have tested this code on both Google Chrome and Firefox. Strangely, it w ...

Populate a dropdown menu using Javascript

[Code] $.ajax ({ 'method': 'GET', 'source': '/bpv-registratie/periods/show_period_list_by_year.html', 'charge': function () { }, 'finish': function (xmlHttp) { ...

The AJAX call is failing to update the state data in my React component

I've recently delved into ReactJS and encountered an issue regarding setting state while using an AJAX request. The AJAX call successfully communicates with the server, receiving a 200 code response, indicating that the API request functions properly ...