Failure to achieve closure - even after thorough study of the concept

I have a countdown that I'm trying to get working during onload, but I'm running into issues with closures. Here is my code:

Check out the fiddle here

for (var o in myDates) {
  var myDate = myDates[o];
  var iid = o;
  funcs[o] = function() {
    var dateFuture = new Date();
    dateFuture.setSeconds(dateFuture.getSeconds()+myDate.durationInSecs);
    GetCount(dateFuture,iid);    
  }
  myDates[iid].tId = setTimeout("funcs['"+iid+"']()",myDates[o].delay*1000);
}

The above code is not working as expected due to implicit eval and use of global variables. Below is the workaround that does work, but I want to avoid the global vars and make it more efficient:


<html>
<head>
<script type="text/javascript">

// JavaScript code goes here...

</script>
</head>
<body>
<div>
<span id="d0" style="background-color:red">!!</span>
<span style="float:right¨;background-color:green" id="d1">??</span>
</div>
</body>

Answer №1

Do not fall into the trap of declaring a closure inside a loop. The inner function will close over the variable myDate, not its value. This can be unexpected since variables in JavaScript have function scope.

To work around this issue, create a closure-maker function that allows you to create a new instance of the variable to close over whenever needed.

INCORRECT

var i;
for(i=0; i<xs.length; i++){
    something = function(){
        f(i);
    };
}
//all closures share the i variable and will have it
//be i=xs.length in the end. We don't want that.

CORRECT

function make_handler(i){
    return function(){
        f(i);
    };
    //each call gets its own copy of i
}
var i;
for(i=0; i<xs.length; i++){
    something = make_handler(i);
}

Alternatively, inline the closure-maker function like this:

var i;
for(i=0; i<xs.length; i++){
    something = (function(i){
        return function(){
            f(i);
        };
    }(i));
}

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

Error encountered during execution of Angular application, specifically TS2305 error?

Hello, I am currently running an angular application by using the 'ng serve' command. I encountered the following error: ERROR in src/app/accounts/account-form/account-form.component.ts(29,3): error TS2305: Module '"/home/prasanth/primecas ...

Searching for values in JSON using jQuery's autocomplete feature

I have implemented jquery autocomplete with a json request in my code. Here is the code snippet for the autocomplete feature: $("#company_name").autocomplete({ source: function( request, response ) { $.ajax({ url: "https://ur ...

Failing to utilize callback functions results in forgetting information

I am facing an issue with my code where changes in the parent component trigger a re-render of the child element. The Menu component is supposed to appear on right-click on top of the placeholder tag, but when it does, the entire parent component flicker ...

React - Render an element to display two neighboring <tr> tags

I'm in the process of creating a table where each row is immediately followed by an "expander" row that is initially hidden. The goal is to have clicking on any row toggle the visibility of the next row. To me, it makes sense to consider these row pa ...

Troubleshooting: Issue with AngularJS ng-click functionality within Modal

My Modal doesn't open when the button inside it is clicked. The ng-click function in the js file is not being called without any error messages. However, outside of the Modal, the ng-click works fine. <div class="container-fluid" ng-app="app" ng- ...

Issues arise when using the select element

Struggling with submitting my list of items from a select in AngularJS. This is my first time posting here and I'm still finding my way around. The issue lies in using ng-repeat in my HTML to display all items. When the screen loads, it only shows: { ...

Exploring the Implementation of Conditional Logic Using Variables in ReactJS

I have a current project in Reactjs where I am extracting the current url/hostname. My goal is to utilize this URL within an if-else statement - meaning, if the url="/" (home page) then display the first header, otherwise display the second hea ...

Transform the angular code in order to execute innerHTML functions

function campform() { $.ajax({url: "{{ path('campform') }}", success: function(result){ $("#respuesta").html(result); }}); } I am having trouble with the angular code in the result I received. Can anyone provide guidance on how t ...

Stopping the Bootstrap carousel when an input is focused

I have a Bootstrap carousel with a form inside. The carousel is set to pause when hovered over, but I noticed that if the cursor leaves the carousel while typing in the inputs, it goes back to its default cycle of 5000ms. I want the carousel to remain pau ...

Deactivate the node-xmpp client

I have been exploring the functionalities of node-xmpp and node-simple-xmpp in order to create a basic client. Everything seems to be working well, except for the disconnection. Following the example from simple-xmpp, I have created the following file: ...

Traversing through asp:GridView information with javascript

Is it possible to iterate through the data in an asp:GridView on the Client-side using JavaScript? If so, I would like to understand how this can be achieved... My objective is to extract the values of two fields in the Grid and add an image to each row b ...

What is the best way to implement a Fibonacci sequence using a for...of loop?

**Can someone show me how to generate Fibonacci numbers using the for...of loop in JavaScript?** I've tested out the following code and it's giving me the desired output: function createFibonacci(number) { var i; var fib = []; // Initi ...

What is the best way to restrict the input year on @mui/x-date-pickers to a certain range?

Is there a way to restrict the input year range when using @mui/x-date-pickers? I want to limit it from 1000 to 2023 instead of being able to enter years like 0000 or 9999. https://i.stack.imgur.com/0p6j3.jpg I have tried adding a mask to InputProps in my ...

Unable to switch checkbox state is not working in Material UI React

I am experiencing an issue with the Material UI checkbox component. Although I am able to toggle the state onCheck in the console, the check mark does not actually toggle in the UI. What could be causing this discrepancy? class CheckboxInteractivity exten ...

What is the best way to design a drop-down suggestion list similar to Google's?

This question is still in the theoretical stage, but it's something I'm definitely considering for the long run. When you visit google.com and type in a search query, the site provides suggestions in a dropdown menu. I'm pretty sure they use ...

What is the best way to upload my React project to GitHub without adding the node modules directory?

I'm looking to share my React Project on GitHub, but I don't want to include the node modules folder. What's the best way to go about this? ...

How can one utilize Codemirror code folding while avoiding the use of "[ ]"?

I am looking forward to implementing Codemirror codefolding for folding only braces { and }, as well as comments. However, I am facing an issue where it also folds square brackets [ and ]. Since square brackets are usually part of one-line statements, I do ...

Why does socket.io have trouble connecting when clients are using different IP addresses on separate wifi networks?

I've encountered an issue where socket.io won't connect when clients are on different wifi networks (ip address) using my self-configured Ubuntu Nginx server. Strangely enough, it works perfectly fine on a pre-configured Heroku server. Here is a ...

Keep the websocket connection continuously open

Here is the code snippet I use to connect to a NodeJS web socket: useEffect(() => { let futureResponseFeedAddress = "ws://localhost:/endpoint"; const futureResponseClient = new W3CWebSocket(futureResponseFeedAddress); props ...

Unusual problem arises with styling and element measurement (scrollWidth / scrollWidth) in Gatsby framework

Currently, I am working on a component that splits lines based on the parent container's width without overflowing. Despite successfully implementing this in a sandbox or pure react application (even with custom fonts), I encountered issues when using ...