Animate css style using setTimeout: "in the blink of a moment"

I need help creating a bar (#innerBar) that decreases in width by 1% every second.

Unfortunately, the loop I implemented is not working as expected. The bar goes from 100% to 0% almost instantaneously.

function timer(){

    var timer;

    for(i=100;i>=0;i--){

        timer = i.toString() + "%";

        setTimeout(function({$('#innerBar').css("width", timer)}, ((100-i)*1000));

    }
}

Please note that #innerBar is a DIV with a height of 10px. **Don't forget to call the timer(); function to adjust the width.**

Answer №1

If you want to make sure your code is executed within a closure, consider this example:

function timer() {
  for (i = 100; i >= 0; i--) {
    setTimeout(function(t) {
      return function() {
        var timer = t.toString() + "%";
        $('#innerBar').css("width", timer);
      };
    }(i), ((100 - i) * 1000));
  }
}

timer();
#innerBar {height: 50px; background: green; transition: width 0.2s linear}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="innerBar"></div>


EXPLANATION

I'm curious about what happens inside function(t). How does it work with }(i)? Is it similar to multiplication?

Let's dissect the body of the function passed to setTimeout:

function(t) {
  return function() {
    var timer = t.toString() + "%";
    $('#innerBar').css("width", timer);
  };
}(i)

If we remove the internal logic:

function(t) {
   // do some stuff with t
}(i)

Does this structure ring a bell? It resembles an IIFE, like this simpler version:

(function(a, b) {
    return a + b;
})(2, 3)  // returns 5

In our initial function, it takes one argument, t, and when calling the function, we pass in the iterator i as an argument (thus, i becomes t within the function). As mentioned before, this approach ensures that we retrieve the current value of i instead of its post-loop value.

Answer №2

Just like @Shomz mentioned earlier, that's a solid solution. I wanted to share my approach as well since it avoids creating too many functions, making it lighter on memory. Plus, it eliminates the need to repeatedly search for #innerBar in the DOM and removes the dependency on jQuery.

var size = 100;
var bar = document.getElementById( "innerBar" );

function setSize() {
    bar.style.width = size-- + "%";
    if ( size > 0 ) setTimeout( setSize, 1000 );
}
    
setSize();
#innerBar {
    width: 100%;
    height: 50px; 
    background: green; 
    transition: width 0.2s linear;
}
<div id="innerBar"></div>

Answer №3

Here is a code snippet that should meet your requirements. When the input time is set to 1000, it will gradually decrease the width of an element by 1% every second.

var currentWidth = $('#progressBar').width();

function decreaseWidthByPercentage(time) {
    currentWidth *= 0.99;
    
    $('#progressBar').css("width", currentWidth);
    
    if (currentWidth <= 0.01){
        return;
    } else {
        setTimeout(function() {
            decreaseWidthByPercentage(time);
        }, time);
    }
}

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

Accessing the AppContext in Next.js within the _document file is the

My challenge with using next js is the occurrence of Content-Security-Policy issues due to the inline styles it utilizes. If 'unsafe-inline' is not added to the style-src, you will encounter the error message 'Refused to apply inline style ...

Ensuring Package Security in NodeJS and NPM

Given the immense popularity of NodeJS and how NPM operates, what measures can be taken to prevent the installation of insecure or malware-laden packages? Relying solely on user feedback from sources like StackOverflow or personal blogs seems to leave a si ...

Save the language code (ISO 639) as a numerical value

Currently, I'm working with a MongoDB database and have made the decision to store certain information as Numbers instead of Strings for what I thought would be efficiency reasons. For instance, I am storing countries based on the ISO 3166-1 numeric s ...

Tips for invoking C language code from JavaScript by using the js-ctypes extension in Firefox

I need assistance with developing a Firefox extension that requires calling native C code. Here is my C program code: #include<windows.h> int add(int a, int b) { return(a + b); } And here is my JavaScript code: var {Cu} = require('chrome ...

Cannot Display CSS Background Image Locally

Apologies for the simple inquiry, but I am facing an issue with displaying my background image using background-image:url() in the CSS. Strangely, it does not work with this method, but when I use content:url(); it works just fine. Interestingly, backgrou ...

Stacking issue - elements not properly aligned

Is there a way to move my H1 text below the blue category button instead of beside it? Thank you in advance! http://jsfiddle.net/TDBzN/ <div id="article" class="animated2 fadeInLeftBig"> <div class="article-close"></div> <div c ...

Looking to streamline this intricate grid/table structure with the help of Twitter Bootstrap

I've been experimenting with creating a complex layout using tables in Twitter Bootstrap, but I'm struggling to get it just right – especially when it comes to displaying the number 5! Is there a way to achieve the same layout using divs instea ...

Preserving checkbox states upon click event

<form name="form_name" action="/" method="get"> <% if params["title"].present?%> <% if params["title"] == "1" %> <input type="checkbox" name="title" onclick="this.form.submit();" value="1" checked> ...

Tips for updating model data when integrating jQuery Data tables with ASP.NET MVC

Managing a large amount of data returned from JSON can be complex. To tackle this, I am utilizing jQuery dataTable for sorting, filtering, and pagination purposes. The functionality is working seamlessly for sorting, searching, and paginating the data. H ...

Using a Python list as an argument in a JavaScript function

How can I pass a python list as an argument to a JS function? Every time I attempt it, I encounter the error message "unterminated string literal". I'm baffled as to what's causing this issue. Here is my python code (.py file): request.filter+= ...

No testing detected, ending with code zero - NPM and YARN

After installing node js and yarn, I attempted to run an application/script developed by someone else. However, when running the test, I encountered the following message: No tests found, exiting with code 0 Watch Usage › Press f to run only failed tes ...

Separate the iframe sessions

I am working with 6 iframes from the same domain but with different URLs and subdirectories. Each iframe sets a cookie with the same name but a different value using the HTML header "set-cookie". To prevent interference between these cookies, I need to fin ...

Utilizing React to pass parent state to a child component becomes more complex when the parent state is derived from external classes and is subsequently modified. In this scenario,

I'm struggling to find the right way to articulate my issue in the title because it's quite specific to my current situation. Basically, I have two external classes structured like this: class Config { public level: number = 1; //this is a s ...

It's proving difficult for me to align my header and navbar on the same line

Recently, I've delved into the world of HTML/CSS and encountered a challenge. My goal is to align my header (containing an h1 tag) and navbar on the same line. Ideally, the header should float left with the navbar positioned closely to its left. Howev ...

Challenges arise when creating a complementary php script for a natural language form

I'm a beginner at this and all the PHP I've tried hasn't been successful. I've come across examples of Natural Language forms, but none with functional PHP. While I am familiar with PHP in traditional forms, integrating the two has been ...

I am having trouble updating a record in my database table

I am encountering an issue while trying to update a row in a table using a form. The add button works fine, but I am unable to update it using the update (a tag). Just a reminder: the edit button is located in the last column of each row along with the de ...

Can you show me how to access the elements of a JSON object named "foo.txt" and print them out?

Currently, I am working with JavaScript and JSON. My goal is to retrieve data from an API where objects contain specific details. Specifically, I need to display the details of an object named "foo.txt" which includes elements such as size, raw_url, conten ...

Utilizing CSS to incorporate a background image into HTML code

Is it feasible to utilize pure HTML for the background-image property? Consider the following scenario: The original: background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height=&apo ...

Issue resolved: Mysterious fix found for background images not displaying in NextJS React components

I am having trouble displaying a background image on an element in NextJs using Typescript and Tailwind. I do not believe it is a TypeScript issue since I am not receiving any errors or IntelliSense warnings. Below is the code I am working with: var classn ...

When attempting to assign a 'string' type to the @Input property, I am receiving an error stating that it is not assignable to the 'PostCard Layout' type

Encountering an issue The error message 'Type 'string' is not assignable to type 'PostCard Layout'' is being displayed A parent component named page-blog.component.html is responsible for defining the class styles and passi ...