JavaScript, create a loop that waits for a change in value

I've been attempting to ensure that an API is fully loaded before proceeding, but the test code below doesn't seem to be properly implementing the timeout delay. As a result, it seems to be running through the loop too quickly.

var google = false;
  function test(check = false) {
    if (!check) {
      console.log('appending the api');

      check = true;
    }
    if (check) {
      console.log('checking if api is loaded');
      if(!google){
        console.log('api not yet loaded');
        setTimeout(test(true), 10000);
        return;
      } else {
        console.log('api loaded successfully');
      }
    }
  }

This code should continue to display the two console.log messages until the google variable is set to true.

However, I'm faced with a dilemma as the browser becomes unresponsive due to an excessive number of loops being generated.

Answer №1

The issue lies within this particular line:

setTimeout(test(true), 10000);

To resolve this, you need to pass the function without executing it. If you need to include parameters, follow this format:

setTimeout(function(){test(true)}, 10000);

Answer №2

When using the setTimeout function, it is important to pass in a reference to the function rather than invoking it immediately. For example, use setTimeout(test, 1000, true) instead of setTimeout(test(true), 1000). This way, you are passing the function itself along with any parameters it requires.

According to information from MDN WindowOrWorkerGlobalScope.setTimeout(), the three arguments that should be passed to setTimeout are: the function, the timeout value, and any parameters needed for the function to execute properly. JavaScript functions are considered first class objects, allowing them to be passed around as regular objects. In the incorrect example provided, the function was immediately invoked, passing its return value to setTimeout instead of passing the function itself.

Answer №3

By setting the timeout for the value returned by the test function, you are actually recursively invoking the test function immediately.

To avoid this, you should place test(true) in an anonymous function like this:

var google = false;
function test(check = false) {
  if (!check) {
    console.log('append the api');
    check = true;
  }
  if (check) {
    console.log('check api is loaded');
    if(!google){
      console.log('not loaded');
      setTimeout(() => test(true), 10000);
      return;
    } else {
      console.log('loaded');
    }
  }
}

Alternatively, you can achieve the same result without using arrow functions like this:

var google = false;
function test(check = false) {
  if (!check) {
    console.log('append the api');
    check = true;
  }
  if (check) {
    console.log('check api is loaded');
    if(!google){
      console.log('not loaded');
      setTimeout(function () {
        test(true);
      }, 10000);
      return;
    } else {
      console.log('loaded');
    }
  }
}

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

The animation in threejs using lerp and camera transitions lacks fluidity

Why does linear interpolation pose a problem? When calling zoomCamera() inside an update() function that is being animated, there is a smooth lerp effect. However, when called within the onObjectsClick() function, the lerp is sharp. function onObjectsCl ...

Logs from console.log() statements in Firebase functions are missing

I've encountered an issue with the function below where the console.log() statements do not appear in the Firebase logs. When I remove everything after the db.collection call, the initial console.log() statements are visible. However, once I reintrodu ...

The property 'top' of undefined jQuery cannot be read

Looking for assistance to troubleshoot and fix the code for this script? Here is the HTML code: <div class="img-wrapper item"> <a href="/product/{{$product->id}}/{{$product->slug}}"> <a class="thum ...

When using the mui joy library, obtaining the input value upon submission may result in the retrieval of an "unidentified" response

Struggling to fetch user input for 2FA authentication using the mui JoyUI library. Attempted using e.target and searching for input value with no success. Clearly missing something in the documentation. Also gave 'useRef' a shot, but the code sni ...

Is there a way to implement tab functionality in jQuery UI through an onclick event?

My goal is to enhance an existing jQuery UI Tab container by adding tab information and then updating the contents through re-initialization. To see a demonstration of what I am trying to achieve, take a look at this JSFiddle: http://jsfiddle.net/dmchale9 ...

Generating a bullet list from an array of objects

Looking to create an unordered list with vanilla JS, using an array of objects to populate the list. Struggling a bit on how to accomplish this. Here is my current code: let myObj = [ {name: "Harry Potter", author: "JK Rowling"}, {name: "Hunger Gam ...

Encountering an issue with inability to resolve the 'react-navigation-stack' module. Still seeking a solution to this problem

Having trouble with my react navigation in react native. I've already added npm react-navigation-stack and also npm install --save react-native-gesture-handler react-native-reanimated react-native-screens. The error message I'm getting is: Unab ...

Arrange arrays with multiple dimensions in JavaScript based on their ranges

Seeking assistance on sorting a multi-dimensional array returned from an API to enable users to choose a range based on beats. I'm currently facing challenges with the data my API is returning. var myObj = [{ title: 'title one', be ...

Create a function that can dynamically filter an array of objects and extract specific properties into a new array

Here is the input that I have: [ { "metadata": { "id": 1071, "name": "First" }, "languages": [ { "name": "Alpha", "details": [ { "city" ...

What is the best way to create three distinct fractions in JavaScript that cannot be simplified?

I have a specific requirement to create 3 fractions with the following conditions: The denominator remains constant The numerator must be unique and fall within the range of 1 to three times the denominator The fraction should not be reducible (e.g., 2/6 ...

The Bootstrap carousel spiraled into disarray

I am facing an issue with the basic bootstrap carousel. My goal is to make the slides move every four seconds. The current setup of the carousel code is as follows: $(document).ready(function() { fixCarousel(); }); function fixCarousel() { $('.c ...

Analyzing conditional statements in React with State management

I've been encountering challenges with if statements correctly evaluating, displaying either true all the time or exhibiting unexpected behavior when passing variables or using state variables for evaluation. I realize this might be related to differe ...

How can one effectively restrict the number of tags allowed in a WYSIWYG editor?

It is not enough to limit the tags in a WYSIWYG editor by excluding buttons, as I can still copy page content and paste it into the editor, which it will accept! I am looking for a solution to restrict the allowed tags. For example, I admire how Stack Ove ...

What is the reason behind the requirement in Javascript (ES.next) that a function must be declared as async in order to utilize await functionality?

Shouldn't a compiler or parser be intelligent enough to recognize when a function utilizes await, and automatically convert it to an async function? Why is there a requirement for me to explicitly type the async keyword? It just clutters the code, an ...

What is the best method to delete a value from localStorage using redux-persist?

In my index.js file, I have set up a persist configuration as shown below: import {configureStore, combineReducers} from "@reduxjs/toolkit" import { persistStore, persistReducer, FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER } from 'redu ...

What is the process of invoking a function from a different component in Vue 3?

I attempted to use the $on method and this.$root.$refs.compname_component = this;, but encountered some errors. Please see my code below: formComponent.vue <template> <div v-if="showForm"> create Form </div> </templa ...

Invoker of middleware and stack functions for Express.js with a focus on capturing the response object

It appears that the expressjs app contains a stack of Layer object Arrays. What function is utilized to pass the I am curious about: When a request is sent from the http client, which function is called first and how are the stack array functions with mi ...

Calculate the total of a checkbox and hidden field combination using JavaScript

Checkboxes are often paired with hidden fields to ensure that the HTTP post includes a value even if the checkbox is left unchecked. For instance, when implementing a terms checkbox, both the checkbox and a hidden element can be used: <input type="c ...

Node.js Sparse Array Memory Usage Explained

I created a program that generates arrays and noticed an interesting behavior: var results = []; var i = 1; while (true) { console.log(i++); results.push([]); } However, when I modify the program to create sparse arrays instead of empty ones, it cra ...

Is there a way to modify this JavaScript code so that it can function with a

I have developed a unique audio player that plays random sections of different songs. Currently, it is hardcoded for one song with three intros, a midsection, and three outros. I am looking to create a system where a list of songs can be randomly chosen fr ...