Retrieve the index of several callbacks created within a loop iteration

While working with an API function that requires a callback in a for loop, I encountered an issue where the callback needed to be index-specific. However, I couldn't alter the willCallBack function (as it's part of the API) and didn't want to resort to using global variables.

The code snippet below demonstrates this challenge. The first for loop yielded unexpected results by returning i==4 for all callbacks. The second for loop provided a workaround, but it felt somewhat cumbersome and hacky.

I'm looking for a cleaner solution to pass the value of 'i' into the callback function definition without compromising on the functionality.

var result = '', result2 = '';

// doesn't work; i == 4 for all
for(var i=0; i<4; i++) {
    willCallBack(function(msg) {
        result += msg + i + '\n';
    });
}

// works, but kinda ugly
for(var i=0; i<4; i++) {
    willCallBack(function(i) {
        return function(msg) {
            result2 += msg + i + '\n';
        };
    }(i));
}

// part of API, cant change
function willCallBack(cb) {
    window.setTimeout(cb, 500, "can't change me");
}

// show the results
window.setTimeout(function(){
        alert(result + '\n\n' + result2)
    }, 1000);

Answer №1

Instead of using the "kinda ugly" version, consider implementing a named function that returns the callback rather than using an anonymous, self-executing function. This alternative approach may appear more aesthetically pleasing to you.

for(var i=0; i<4; i++) {
    willCallBack(createCallback(i));
}

function createCallback(index) {
    return function(msg) {
        result2 += msg + index + '\n';
    };
}

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

JavaScript's utilization of local variables and callback functions enables developers to enhance the

After exploring the information in this particular post, it became evident that my issue was different. While working on creating functions for managing mongoDB GridFS, I encountered a perplexing behavior that I will illustrate through a simplified example ...

Determine if all resources on a page in Angular 4 have finished loading by keeping a loader spinning until everything is fully loaded

As part of my work on an Angular app, I am developing a loader to enhance user experience. While the typical approach involves utilizing a boolean parameter for subscribing to HTTP requests, in my case, the service's response consists of multiple ima ...

Best practices for utilizing child component methods within a parent component in VUE

I am working with the ImageUpload.vue component, which is a straightforward Bootstrap modal containing a few methods. I am currently exploring the best approach to utilize one of these methods. Could it be implemented like this: const app = new Vue({ ...

Grunt is throwing an error message of "Cannot GET/", and unfortunately ModRewrite is not functioning properly

I've recently started using Grunt (just began last Friday). Whenever I run Grunt Serve, it displays a page with the message "cannot GET/" on it. I tried implementing the ModRewrite fix but the error persists. Any assistance would be highly appreciat ...

Issue with ng-checked not detecting boolean values retrieved from local storage

I'm working on a code snippet in my controller where I have a checkbox in my HTML with "ng-checked="enterToSend" and "ng-click="enterToSendCheck()" attached to it. $scope.enterToSend = localStorage.getItem('enterToSend'); $scope.enterToSen ...

Revamping the values attribute of a table embedded in a JSP page post an AJAX invocation

I am encountering an issue with displaying the content of a table. The table's data is retrieved via an AJAX request when clicking on a row in another table on the same page. Here is my code for the JSP page: <table id="previousList" class="table" ...

What is the correct way to reset the styling of a web browser element, such as a <button>?

I have come across many sources advising me to reset HTML by manually resetting numerous individual properties, as demonstrated here: https://css-tricks.com/overriding-default-button-styles/ Another approach I discovered in CSS is simply using: button: {a ...

Error in Prisma: Unable to retrieve data due to undefined properties (attempting to access 'findMany')

Recently, I've been working on a dashboard app using Prisma, Next.js, and supabase. Encountering an issue with the EventChart model in schema.prisma, I decided to create a new model called EventAreaChart. However, after migrating and attempting to ex ...

Demonstrating the process of sending a list of items from Angular to an Express API connected to MongoDB

I am currently working on developing an Express Mongo API that is being utilized by an Angular application. My query revolves around posting a list of items. Here is my MongoDB schema: var TestSchema = new mongoose.Schema({ title: String, colors: ...

Error in canvas-sketch: "THREE.ParametricGeometry has been relocated to /examples/jsm/geometries/ParametricGeometry.js"

I recently started using canvas-sketch to create some exciting Three.js content. For my Three.js template, I utilized the following command: canvas-sketch --new --template=three --open The version that got installed is 1.11.14 canvas-sketch -v When atte ...

Is there a way to utilize a single function on two separate div elements?

Looking for a way to optimize my code that contains the addRow() and deleteRow() functions. Currently, I have duplicated these functions for both radio buttons and checkboxes. Is there a more efficient way to achieve this? function addRow(tableID) { ...

The attempt to install myapp using npx create-react-app has failed. The installation has been aborted

Attempting to create a new project using npx create-react-app my-app resulted in an error message saying Aborting installation. https://i.sstatic.net/IhpQJ.jpg Initially, I had node v14.17.1 installed. Upgrading to the latest version 16.4.0 did not resol ...

Exploring JavaScript's Modules, Enclosures, and Scoping

Utilizing a closure pattern to compartmentalize my code: (function(root) { // MODULE CODE HERE if (typeof module !== 'undefined' && module.exports) { // CommonJS /* var dependencies = require(...) */ module.exports = myModu ...

Error: Kinetic.js cannot upload image to canvas

There must be something simple that I'm missing here. I've checked my code line by line, but for some reason, the image just won't load. var displayImage = function(){ var stage = new Kinetic.Stage("imgarea", 250, 256); var layer = new ...

Looping animations using AngularJS

I have implemented a custom directive to trigger an animation on an element when a specific field is empty on the page. However, I am facing an issue where the animation only works once when the user clicks the button with the directive. Subsequent clicks ...

Node.js retrieves a single row from a JSON array with two dimensions

I am working with a two-dimensional JSON array and I am able to retrieve data from the first dimension using data["dimension-1"], but I am struggling to access data from the second dimension using data["dimension-1"]["dimension-2"]. What is the correct m ...

Selenium WebDriver keeps crashing with a newSession error after around 70 seconds of running

Recently, a perplexing error surfaced in my previously functional project without any changes to the code. The sudden appearance of this issue may be attributed to a FireFox update or a dependency failure. To help troubleshoot the abrupt cessation, I added ...

TypeScript error: Cannot find property 'propertyName' in the 'Function' type

I encountered an issue with the TypeScript compiler when running the following code snippet. Interestingly, the generated JavaScript on https://www.typescriptlang.org/play/ produces the desired output without any errors. The specific error message I recei ...

Exploring Karma and Jasmine for Testing Angular Controllers Module

In an attempt to test my application, I have each controller defined in its own module rather than as a controller of the main app module, and then loaded as a dependency of the main app module. While running a test to check if the loginController is defin ...

Customize your click event with conditional styling in React

When the onClick event is triggered, I am attempting to modify a class by calling my function. It appears that the function is successfully executed, however, the class does not update in the render output. Below is the code snippet: import React from &ap ...