Javascript closures: a common pitfall

I'm facing an issue with my code where it is not behaving as expected. Although I believe the code itself is correct, there seems to be a problem that I'm unable to identify. The goal of the code is to display numbers 10 through 0 with a 2-second interval between each number, i.e., 10-9-8... and so on. The current behavior is that it displays the numbers in ascending order instead of descending. I would prefer to use a for loop rather than seeking a workaround solution. Below you can find the snippet of my code:

function fadeOut(elem)
{
    for( var i=10; i>0; i-- )
    {
        (function(index)
        {
            setTimeout(function()
            {
                console.log(index);
            }, index * 2000);
        })(i);
    }
}

Answer №1

Start off by initiating a countdown: "After 10 seconds, display '10'."

Continue this pattern with decreasing numbers: "After 9 seconds, show '9'."

This sequence goes on until you reach the end: "After 1 second, reveal '1'."

Finally, after 999 milliseconds from the start, the last command is executed and it displays "1".

Give the following code snippet a try:

function fadeOut(elem)
{
    for( var i=10; i>0; i-- )
    {
        (function(index)
        {
            setTimeout(function()
            {
                console.log(index);
            }, (10-index) * 2000);
        })(i);
    }
}

Answer №2

There are a total of 10 timeouts created, each with a decreasing time interval:

  • After 10 seconds - log 10
  • After 9 seconds - log 9
  • After 8 seconds - log 8
  • After 7 seconds - log 7

...

  • After 1 second - log 1

The objective is to extend the duration while reducing the counter value as demonstrated by the following JavaScript function:

function fadeOut(elem)
{
  for ( var i = 10; i > 0; --i )
  {
    (function(index)
     {
      setTimeout( function(){
        console.log(index);
      }, (11-index)*2000);
    })(i);
  }
}
<button onclick="fadeOut(this)">Click</button>

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

Show a variety of months using a datepicker arranged neatly in rows and columns

I need to display 13 months using multidatespicker. I achieved this with the following code: $(document).ready(function(){ $('#my_calendar').multiDatesPicker({ numberOfMonths: [4, 4], dateFormat: 'dd-mm-yy&a ...

Sort out online notifications using client-side technology

When a notification is sent to a specific topic, such as... const message = { data: { cost: 49 }, topic: 'apple' } admin.messaging().send(message) The question revolves around controlling/filtering notifications based on user-defined criter ...

What is the reason behind the delayed mutation of the state when invoking the setState method in React?

Currently diving into the Forms section within the documentation of ReactJS. Just implemented this code snippet to showcase the use of onChange (JSBIN). var React= require('react'); var ControlledForm= React.createClass({ getInitialState: f ...

The operation of executing `mongodb - find()` does not exist as a function

I am having trouble printing all documents from the "members" collection. I attempted to use the find() function, but encountered an error stating that find() is not a function. Here is a snippet from member_model.js located in the models/admin folder: v ...

Strategies for managing extended API requests during view loading

Hello, I am currently working on a Rails application focused on displaying user-generated content. Within one of my controllers, specifically the #show action, I am making an API call to generate recommendations for "up next" content. This API call typical ...

encountering a problem integrating react-dropzone into a project using react-16.13.1

I'm having an issue adding the package https://www.npmjs.com/package/react-dropzone to my TypeScript React project using Yarn as the package manager. I ran the command yarn add @types/react-dropzone, but it ended up installing a deprecated package h ...

What is the best way to invoke a JavaScript function after an event or from a user interface?

I am struggling to call a JavaScript subroutine on the client-side after the server has completed its task. Even though I have tried putting breakpoints in <% ... %> areas between <script...> and </script>, it seems that VS2010 does not a ...

Struggling to load Bootstrap Tooltip within the Span Tag that encapsulates the Img tag

I am currently working on implementing a tooltip popup for images within an unordered list. I have wrapped the images in span tags with the necessary attributes, but instead of seeing the expected tooltip, I am only getting a normal tooltip when hovering o ...

Python script utilizing Selenium to load only JavaScript content and excluding full HTML rendering

As I navigate through the link , I am on the lookout for the search bar marked with the class "search-field". The HTML snippet in question is as follows: from selenium import webdriver import time driver = webdriver.Firefox() driver.get("https://www.takea ...

The passage of time becomes distorted after a few hours of using setInterval

I created a simple digital clock using JavaScript to show the time on a TV screen. However, after several hours of running, I noticed that the displayed time gets off by a few seconds (around 30 or more). Below is the code snippet I used: getTime() { ...

Sequence of promises: The parent promise does not wait for the child promise to be executed before moving on

I am retrieving data from a particular mongoDB collection. Within that response, I obtain the ID associated with another collection's data and merge it into one cohesive object. Take a look at my code snippet below. It seems like it's not waitin ...

Encountering a 404 error when utilizing ngx-monaco-editor within an Angular application

I have been encountering an issue while attempting to utilize the editor within my Angular 8 application. Despite researching similar errors on Stack Overflow and GitHub discussions, I haven't found a solution yet. Here's how my angular.json asse ...

What is preventing node from locating the module?

My attempt to incorporate a currency into my bot has hit a snag. When I run node dbinit.js, it returns an error saying "module not found." Below is the script I'm using and the specific error message: const Sequelize = require('sequelize'); ...

Sending parameters with HTTP GET requests in AngularJS

Currently, I am attempting to pass parameters using the GET method in AngularJS. $scope.callMethod = function(url , paramName1, paramName2 ,paramValue1 , paramValue2) { $http.get('rest/'+url+'?cd='+ (new Date()).getTime(), ...

I'm unable to resolve all parameters for xxx -- unit testing using jest

I recently encountered an issue with a test in jest that is failing and displaying the following error message: Error: Can't resolve all parameters for LoginService: (?). at syntaxError (/Users/wilson.gonzalez/Desktop/proyecto_andes/external/npm/nod ...

In a jQuery conditional statement, selecting the second child of the li element for targeting

I'm encountering an issue where I can't target the second child of an li element and use it in a conditional statement. Are jQuery conditionals not compatible with li:nth-child(2)? if($(".steps ul li:first-child").attr('aria-selected') ...

Updating a Parent component from a Child component in React (Functional Components)

My functional component RoomManagement initiates the fetchRooms function on the first render, setting state variables with data from a database. I then pass setLoading and fetchRooms to a child component called RoomManagementModal. The issue arises when t ...

Issue with onClick event not firing when using option tag in React

onClick event seems to have an issue with the <option> tag. How can we successfully use the onClick event with the select option tags while assigning different parameters to each option? async function setLanguage(language) { ...

Bootstrap tab content getting shifted downwards

Having an issue with the Tab plugin in Bootstrap on a particular page. The tab body is being pushed down 400px below the actual tabs. This behavior is only occurring on this specific page, while most other pages using the same plugin are functioning fine. ...

What is causing my Three.js scene to appear pitch black?

I am embarking on my first three.js project, but unfortunately my scene is appearing entirely black. I am utilizing Vite as my local server. Below is the JavaScript code I am currently using: import * as THREE from 'three' //Scene const scene = ...