Decoding the mechanism of while-loops in Vue through the lens of setTimeout

I'm fairly new to Vue and I find this concept really confusing.

Imagine having a while loop inside a method like this:

methods: {
  test: function() {
    counter = 0;
    while( counter < 10 ){
      console.log( counter );
      counter++;
      window.setTimeout( function() {
        console.log( 'Test' );
      }, 1000)
    }
  }
},
mounted() {
  this.test();
}

When you run it, the output in the console looks like this:

0
1
2
3
4
5
6
7
8
9

(10) Test

But shouldn't the output actually be:

0
Test
1
Test
2
Test
3
Test
4
Test
5
Test
6
Test
7
Test
8
Test
9
Test

... with a one-second delay between each item?

The reason I'm asking is because I need to wait for data from an API before running a function.

One suggestion recommends using arrow functions for setTimeout, but I haven't seen any difference in results.

I've also studied Vue's lifecycle, but didn't find the solution there either.

Answer №1

The while loop in this scenario counts very quickly (less than 1 second), so by the time the timeout function is triggered, the rest of the code within the loop has already executed, printing numbers from 0 to 9. Subsequently, each timeout also reaches its countdown and prints 'Test' consecutively. As a result, 'Test' is printed 10 times in succession, displayed as (10) in the console instead of being literally printed 10 separate times.

This behavior occurs because when window.setTimeout is called, the specified code runs after a certain amount of milliseconds - independently in parallel with the remaining code execution.

To achieve the desired outcome, it is advisable to run the code directly without utilizing timeouts:

methods: {
  test: function() {
    counter = 0;
    while( counter < 10 ){
      console.log( counter );
      counter++;
      console.log( 'Test' );
    }
  }
},
mounted() {
  this.test();
}

If you intend to have a 1-second delay between displaying each number, consider implementing a recursive function like the following:

test(0);

function test (counter) {
    if (counter < 10) {
       console.log( counter );
       counter++;
       console.log( 'Test' );
       window.setTimeout( function() {
          test(counter);
       }, 1000)
    }
}

Ensure to set an initial or default value of 0 for this operation.

Answer №2

The optimal choice would be to implement a Promise for this task. The function getApi needs to be updated to fetch and process the API using a promise for asynchronous execution, allowing the use of then once the data is loaded...

methods: {
  test: function() {
    this.retrieveData().then((data) => {
       // Action after API load | data === 'example data' 
    });
  },
  retrieveData: function(){
    return new Promise((resolve) => {
      resolve('example data');
    });
  }
},
mounted() {
  this.test();
}

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 jQuery HTTP Post function suddenly stopped functioning properly, only working when lengthy strings are entered

Just starting out with web development. I have a bootstrap page featuring a form for users to input data. The form includes two text boxes, one radio button, and one dropdown menu. My goal was to collect this input data and create a JSON object to POST it ...

Creating a dynamic list in HTML by populating it with randomly selected words using JavaScript

Check out my awesome code snippet function wordSelect() { var words = ["Vancouver", "Whistler", "Surrey", "Victoria", "Kelowna"]; //List of randomly-selected words from above var selectedWords = []; for(let i = 0; i &l ...

"Discovering the method to showcase content based on page number or when the 'previous' or 'next'

Here is how my Vue component looks like: <template> ... <b-col v-for="item in items" v-bind:key="item.id" cols="2"> ... <strong slot="header" class="text-dark" :title ...

To clear the previous result of an AJAX call in JavaScript, reset the function or variable

I encountered a problem previously, and now another issue has come up. It appears that the previous result from my ajax JavaScript is still being displayed, and I need to prevent that from happening. I've tried deleting the variable, setting it to und ...

Tips for reducing the size of the sidebar when navigating to a specific page

I have a sidebar that I want to minimize when the user enters the index page. There is a button in the sidebar for that: <a class="mobile-menu" id="mobile-collapse" href="javascript:"><span></a> How can I au ...

An alternative way to update the radio button's checkability status using the :checked or :unchecked attributes

Within the code snippet below, there are two radio buttons present. Initially, both of them are unchecked. When the first radio button is checked, the log message in change_() function prints "male". On the other hand, when the second radio button is check ...

Emberjs promises are enhanced with a filtering feature

My goal is to develop a search functionality using a JSON API. After following tutorials and successfully implementing it with provided examples: export default Ember.ArrayController.extend({ searchText: null, searchResults: function(){ ...

Is it possible to set up a server with 'app' as the designated request handler?

When working with NodeJS, server creation can be done simply by using: http.createServer(function(req,res) { /* header etc. */}); However, as I delved into using express, the server was automatically created for me. Moving on to learning about sockets, I ...

Detect prohibited terms with Jquery

Check out this jsfiddle. I need assistance with a feature where certain specific words trigger an alert for the user when typed. Currently, if I type a phrase like I love ants, the entire line gets alerted. However, I want only the word ants to trigger th ...

Pull data from a subdocument using Mongoose

Here is the content of my document: { password: '87654321', title: 'Organization A', members: [ { tier: 1, joinedDate: Sun May 12 2013 00:00:00 GMT+0200 (CEST), user: 543fc462ed385e5e77a98d56 }, { ti ...

Capture all Fetch Api AJAX requests

Is there a way to intercept all AJAX requests using the Fetch API? In the past, we were able to do this with XMLHttpRequest by implementing code similar to the following: (function() { var origOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.p ...

Exporting functions using reactjs and babel

I'm currently working on a project that involves using reactjs, transpiled by babel with es2015 and react transforms configured in my .babelrc file. In the initial stages of refactoring, I realized that many of the classes should actually be functions ...

Utilize INTERFACE-driven capabilities in ReactJS to dynamically render components based on a variable

How can interface-based functionality be used to render components based on tab selection? If we have 3 components as follows: OneTimeOnlyScheduleComponent DailyScheduleComponent WeeklyScheduleComponent We aim to have all of these components implement t ...

Link JSON in JavaScript using field identifiers

I've been working on incorporating JSON data into my JavaScript code, and the JSON structure I am dealing with is as follows: { "status":"ok", "count":5, "pages":1, "category":{ "id":85, "slug":"front-page-active", "title":"Front ...

Using jQuery to duplicate a div multiple times when scrolling

I'm looking for a way to continuously duplicate the contents of a div as I scroll, creating the illusion of an infinitely scrolling page. My current markup looks like this and you can also find a working example in this fiddle https://jsfiddle.net/guh ...

Using JQuery to enable checkbox if another is selected

I have a single checkbox that reveals a hidden div when checked. Inside this div, there are two additional checkboxes. My goal is to disable the initial checkbox if either of these two checkboxes is checked. Here's the HTML code snippet: <p> ...

Adding a background behind the currency symbol before the textbox field

I need to customize a text field like the one shown in the image below: https://i.sstatic.net/gu3JA.png After making some quick adjustments, I ended up with the following result. My main concern is now the background of the currency symbol. https://i.ss ...

Best method for creating HTML elements with jQuery

I've come across various styles and methods for creating elements in jQuery, each with its own unique approach. I am interested in discovering the most effective way to construct elements and whether a specific method stands out as superior for any pa ...

Changing a string into a multi-dimensional array using javascript

The following data is retrieved from the REST API: [[5671, 204], [5673, 192], [5674, 120], [5683, 120], [5684, 192], [5685, 204]] When using typeof in JavaScript on the above, it returns a string. To convert it to a multi-dimensional array: <script ty ...

Troubleshooting not locating view files in ExpressJS and implementing client-side JavaScript and CSS deployment in ExpressJS

My JavaScript file is located in the same directory as my HTML file, and I am trying to render it. I'm unsure of what I may be missing. How difficult could it possibly be? var express = require('express'); var app = express(); app.engine( ...