Asynchronous callback causing changes to a JavaScript variable

  let numbers = ["1", "2", "3"];
  const squareNumber = (i, cb) => {
    i = parseInt(i);
    setTimeout(() => cb(null, i * i), 100);
  }

  for (let i of numbers) {
    squareNumber(i, (err, result) => {
      console.log(i + " " + result);
    });
  }

  // output:
  // 3 1
  // 3 4
  // 3 9

  // expected:
  // 1 1
  // 2 4
  // 3 9

If I remove setTimeout, I can get the expected result.

Or it can be written like this:

for (let i of numbers) {
  ((i) => {
    squareNumber(i, (err, result) => {
      console.log(i + " " + result);
    });
  })(i);
}

Could this be a bug in JavaScript?

Answer №1

This is the modified code in Javascript that provides the same output (view fiddle here: http://jsfiddle.net/99obrntp/)

var numbers = ['1','2','3'];

function squared(num, callback){
    num = parseInt(num);
    setTimeout(function(){
        callback(null, num*num);
    }, 100);
}

for(var j=0; j<numbers.length; j++){
    var val = numbers[j];
    squared(val, function(error, res){
        console.log(val, res);
    });
}

The calculation of the squared values is accurate, but there is an issue with the console.log() function. The problem arises because the callback is not executed until after the loop finishes (due to the setTimeout function). This results in the val variable being assigned as '3' before any console outputs are made. To resolve this, you should pass the value to the callback function. Here's how:

var numbers = ['1','2','3'];

function squared(num, callback){
    num = parseInt(num);
    setTimeout(function(){
        callback(null, num*num, num);
    }, 100);
}

for(var j=0; j<numbers.length; j++){
    var val = numbers[j];
    squared(val, function(error, res, initialVal){
        console.log(initialVal, res);
    });
}

Updated fiddle link: http://jsfiddle.net/3sdjgzv1/

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

What is the best way to loop through an array of strings and make them all plural?

I am currently working on a challenge where the objective is to take an array and pluralize each element by adding an 's' at the end of it. Here's my attempt so far, but I suspect that there might be mistakes in my code: var pets = [' ...

JavaScript: changing text to numbers within an array

Looking at this array of strings: ["5:17", "8:22", "3:34", "5:23", "7:12", "7:24", "6:46", "4:45", "4:40", "7:58", "11:51", "9:13", "5:50", "5:52", "5:49", "8:57", "11:29", "3:07", "5:59", "3:31"] I'm curious, how do you suggest converting the ...

JavaScript: Exploring the basics - how to insert a function argument into an empty array

I am currently struggling with a question and unsure of what to do, so I am seeking help to solve the following challenge: Begin by creating an empty array. Next, create a function that takes in one argument. Within this function, add the argument to the ...

Tips for creating an angularjs login page as the initial page

I am new to working with AngularJS and I have been experimenting with the generator-angular-fullstack, My goal is to have the login page load first instead of the main page. After playing around with the code, I found a solution by adding 'authentica ...

The execution of form validation and any following code is halted

I have an update form that is called inside a modal on my main page. Whenever I click on it, an XMLHttpRequest triggers the edit page containing the form with the stored data values. Everything seems to work fine except for the form validation and AJAX use ...

Enabling clients to access all static files from a Node.js + Express server

My index.js file serves as a node.js server : var express = require('express'); var app = express(); const PORT = process.env.PORT || 5000; var serv = require('http').Server(app); app.get('/', function(req, res) { res.sen ...

What is the best way to align two bootstrap buttons next to each other?

Is there a way to align buttons on a modal side by side? One button is a download link and the other a mirror link. I attempted to use a custom class with CSS property "display: inline-block;" but it did not work as expected. Any suggestions on how to achi ...

What is the best way to search for documents that have all conditions met within a sub-array entry?

My rolesandresponsibilities collection document is displayed below: [{ "_id": { "$oid": "58b6c380734d1d48176c9e69" }, "role": "Admin", "resource": [ { "id": "blog", "permissions": [ " ...

` Why isn't Glide.js functioning correctly when incorporated into a Bootstrap 4 modal component?`

I'm currently utilizing Glide.js and a Bootstrap 4 modal on our team page to showcase the biography of the selected team member. This functionality is achieved by extracting the attribute of the clicked team member and using it as the startAt: index f ...

I'm having trouble resolving the issue in my React App after attempting to export a functional component. How can I troubleshoot and

Since the first week of this online course on Coursera.org, I've been struggling to get my React app to display. Even after watching videos and revising the code multiple times based on Google search results, I couldn't make it work. Despite seek ...

Is it possible to invoke a PHP function from within JavaScript?

Check out my JavaScript code: <script> $(document).ready(function(){ $(".five").click(function(){ <?php echo updatepoints();?> }); }); </script> Now take a look at my PHP code: <?php function updatepoints() { mysql_connect("localhos ...

Implementing input validation in a Symfony v5.2 project using Jquery-validation v1.19.3 and Bootstrap v4.6

INTRODUCTION In my project using Bootstrap v4.6, jQuery v3.5.1, and jquery-validation v1.19.3 with Symfony v5.2, I am implementing user input validation. EXPECTATION I aim for consistent validation whether by JavaScript or PHP. STEPS TAKEN Following an ...

Retrieve vuex state in a distinct axios template js file

I have encountered an issue with my Vue project. I am using Vuex to manage the state and making axios requests. To handle the axios requests, I created a separate file with a predefined header setup like this: import axios from 'axios' import st ...

What is the proper method for effectively employing destructuring?

I'm trying to figure out how to properly return state with a fetched array using the spread operator. Here is my reducer code snippet: function themes(state = [], actions){ switch(actions.type){ case FETCH_THEMES_SUCCESSFULLY: const { th ...

Steer clear of redundant information within an array located within a recursive function

Currently, I am facing a challenge with a recursive type of function that dynamically runs based on a returned query. My goal is to prevent duplicate or redundant data in my array during each recursive loop by filtering out any duplicates. Here is the cod ...

Equal-sized tiles in Highchart treemaps

I'm attempting to display JSON data in treemaps with equal squares. I discovered that the highchart-treemap library offers four built-in algorithms - squarified, slice and dice, stripes, and strip. However, none of these algorithms provide me with the ...

Traverse an array containing nested objects using Javascript

I am facing difficulty printing out objects stored in an array. When I console log, this is the result: console.log(product.categories) https://i.stack.imgur.com/YVprQ.png How can I iterate through these nested objects to display them individually like t ...

using jQuery to display the image when clicked on

Is there a way to make an image display in full screen when clicking on its thumbnail? The images are hardcoded using the IMG tag and have the class .imagethumb. Currently, the images are displayed as thumbnails. When clicking on a thumbnail, I would lik ...

Discover supplementary characters to incorporate into a JavaScript string

I am facing a challenge with identifying three added characters in the second string that are not present in the first string. These added characters could be located anywhere within the string. For example: string1 = "hello" string2 = "aaahello" // =&g ...

Tips for creating a wavy surface on a cylinder using three.js (with images)

I've been working on giving my cylinder geometry a wavy surface, aiming for a look like this: https://i.sstatic.net/aCaV7.png However, after implementing the following code, it ended up looking quite distorted as shown in these images: https://i.ssta ...