The mechanics of closure in the code snippet explained

As a beginner, I find myself struggling to understand the code snippet below.

for (var i=1; i<=5; i++) {
    console.log('ooo');
    setTimeout( function timer(){
        console.log( i );
    }, i*1000 );
}

The output generated by this code segment looked like the following:

ooo
ooo
ooo
ooo
ooo
6
6
6
6
6

I would greatly appreciate any help in clarifying the workings of this code. Thank you!

Answer №1

for (let j=1; j<=5; j++) {
    console.log('ooo');
    setTimeout( function timer(){
        console.log( j );
    }, j*1000 );
}

When the setTimeout() is invoked in this code, the for loop will have completed, and each function will reference a different value of j ranging from 1 to 5.

function closure(j){
    setTimeout( function timer(){
        console.log( j );
    }, j*1000 );
}

for (let j=1; j<=5; j++) {
    console.log('ooo');
    closure(j);
}

This implementation will output values of j from 1 to 5 as each function can access only its specific value of j.

Answer №2

The expected outcome should resemble the following: Please follow these instructions carefully 1. The code will output "000" <= 5 times. - In each iteration of a for loop, the variable i is incremented. When the timer function is first executed, i has been increased to 127 and then to 6.

16:57:40.946  ooo
16:57:40.946  ooo
16:57:40.946  ooo
16:57:40.947  ooo
16:57:40.947  ooo
16:57:40.947  127
16:57:41.949  6
16:57:42.947  6
16:57:43.951  6
16:57:44.947  6
16:57:45.950  6

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

Remove input fields that were generated upon clicking a button

I'm facing an issue with my code that allows me to add inputs using @click="addInput()". However, I am struggling to delete specific inputs using @click="deleteInput(). When I try to delete an input with this.inputs.splice(index, 1), on ...

Storing user data on the client side of a website is most effectively accomplished by

I am looking to incorporate the following features: I would like to personalize the user experience by greeting them with their login name on the webpage (e.g. 'Hello, Fred!'). I also want to display or hide certain content based on the user&apo ...

What could be causing the element.style.FontSize to not be effective on classes that have been looped through and stored in an array created with querySelectorAll beforehand?

Greetings Stackoverflow Community, Today, I'm facing an issue related to JavaScript and WordPress. I have a JavaScript script named setDynamicFontHeight.js, as well as PHP documents named header.php and navbar_mobile.php, which simply executes wp_nav_ ...

Is there a way to limit the width of the input box once it reaches a specific pixel measurement?

One issue I'm facing involves the following code snippet: <html> <head> <script type="text/javascript"> function Expand(obj){ if (!obj.savesize) obj.savesize=obj.size; obj.size=Math.max(obj.savesize,obj.v ...

Is there a workaround available for the JavaScript timeout and interval functions in XPages SSJS?

While utilizing XPages' server-side JavaScript (SSJS), I find myself longing for the timing/scheduling features like setTimeout, setInterval, clearTimeout, and clearInterval. Has anyone developed a polyfill to add these crucial functions to SSJS? ...

Issue with Mongoose's deleteOne() and deleteMany() methods not functioning as intended

While working on my learning project to build a simple web application for managing todos, I encountered an issue with deleting entries in my MongoDB database. I created a basic JavaScript app using the mongoose module to replicate the problem. The app cre ...

Issue: Error encountered while trying to use the removeAttribute() function in Selenium and Java: missing closing parenthesis after argument list

WebElement removeReadOnly=driver.findElement(By.xpath("//input[@id='mat-input-0']")); js.executeScript("document.getElementBypath('//input[@id='mat-input-0']').removeAttribute('readonly');",&quo ...

Avoid the occurrence of the parent's event on the child node

Attempting to make changes to an existing table created in react, the table is comprised of rows and cells structured as follows: <Table> <Row onClick={rowClickHandler}> <Cell onCLick={cellClickHandler} /> <Cell /> ...

Footer positioned correctly with relative DIV

I find myself in a state of complete confusion. Coding is not exactly my forte, so I suspect I have made a significant error somewhere that is causing the following issue: My goal is to create a sticky footer. The footer does indeed stick to the bottom of ...

Creating code for both the PC and mobile website by utilizing the user agent

I need to customize the CSS for my website, and I have a specific question: If a user is accessing my web page via a computer, the CSS should be as follows: <link rel="stylesheet" href="/pc.css" type="text/css" media="all" /> However, if they are ...

Employing the Map function in React leads to an error that is undefined

Upon simplifying my code, it seems that I am encountering an unresolved issue with the map function being used in different locations. I have noticed that code from examples running on platforms like Codepen does not work in my locally created react app p ...

Swapping out an entire chunk of information in a JSON document

Currently, I am seeking a solution to update specific data in a JSON file without altering any other sections within it: { "task": [ { "id": 5, "title": "dave", "description": "test" }, { "id": 6, "title": "fdds ...

Exploring the power of Angular's ng-repeat to generate hierarchical lists

I am looking to display a structured list of layers and sublayers by looping through an object using ng-repeat. var lyrslist = [ { layername: "Base Maps", layertype: "layer" }, { layername: "Open Street Map", layertype: "sublayer" },    { layer ...

Why did my datatable append HTML only to get suddenly refreshed?

Having trouble figuring out why my code isn't working as expected. I believe the logic is correct, but for some reason the custom HTML doesn't persist after the second click. The goal is to display my custom HTML after a new tr element is added. ...

Are there any security concerns involved in creating a game using a combination of JavaScript, Electron, and Three.js?

I'm not looking to create anything on the scale of an MMORPG, just a small game similar to Faster Than Light. Is there a way to protect against cheat engine or prevent users from running their own JavaScript in the game, considering anyone can access ...

What tips should be followed when setting up the stencil repository?

Is there a preferred method for defining fields when setting up a Stencil store? The documentation provided online primarily showcases examples with numbers, but what about situations involving objects, strings, or booleans? Should we use the 'as&apo ...

Exiting shell sessions may involve NPM, Supervisor, and Nohup

I'm currently using Node LTS and I have a script that needs to run continuously. Even after disconnecting from SSH, I want it to keep running. I recently came across a node package called supervisor which is supposed to restart the process if it crash ...

Transforming NIF to OBJ within the Blender 249.2 software results in an object that is not visible

I am currently utilizing Three.js for rendering Fallout 3 assets in WebGL. Check out the JavaScript code for a similar object rendering here. Most objects are loading fine along with their normals, except for the brahmin... While the texture and normals a ...

Display "Page Loading Error" when submitting a form with jQuery Mobile via JavaScript

While working on my jQM project, I encountered an issue with form submission. Instead of using the "action" URL to submit the form, I opted to use JavaScript to submit the form after validation by another JS addon. Once validated, the form is submitted usi ...

Press the second form submit button after the completion of another Observable

Below is the unique process we aim to accomplish using solely RXJS Observables: Press Login button (form with username & password). We bind Observable.fromEvent with our form. Upon submitting the form, call loginUser() to send an http request to serv ...