The setInterval() function appears to be malfunctioning

My code dictates that the counter should stop once it reaches 60%, but instead, it continues counting beyond that point indefinitely. How can I rectify this issue and make sure it halts at 60%?

 var i = 0;
 function counter(tag_name, precent, varname) {
     i++;
     $(tag_name).html(i + "%");
     if (i == precent) clearInterval(varname);
 }
 var p1 = setInterval(function () {
     counter("#p1", 60, p1);
 }, 50);
 var p2 = setInterval(function () {
     counter("#p2", 60, p2);
 }, 50);
var p3 = setInterval(function () {
     counter("#p3", 60, p3);
 }, 50);
div {
    border:solid 1px black;
    margin:1px;
    width:50px;
    height:30p;
    float:left;
}
#m1, #m2, #m3 {
    width:200px;
    height:60px;
    float:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="m1">
    <div id="b1">d1</div>
    <div id="p1">%</div>
</div>
<div id="m2">
    <div id="b2">d2</div>
    <div id="p2">%</div>
</div>
<div id="m3">
    <div id="b3">d3</div>
    <div id="p3">%</div>
</div>

Answer №1

There are a couple of issues to address:

  1. The use of clearInterval(varname); may not work as expected because it passes the current value of the variable when it is called, not necessarily the value at that moment. This can be resolved by using object properties or finding a better solution.

  2. All counters share the same i variable, causing inconsistent incrementing and preventing all counters from stopping at the desired percentage value.

  3. A small typo exists: it should be "percent," not "precent".

A suggested improvement would be to use separate i variables, let counter manage its own operations, and employ a chain of setTimeout instead of setInterval:

function counter(tag_name, percent) {
    var i = 0;

    run();

    function run() {
        i++;
        $(tag_name).html(i + "%");
        if (i < percent) {
            setTimeout(run, 50);
        }
    }
}
counter("#p1", 60);
counter("#p2", 60);
counter("#p3", 60);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>

If sharing the i variable is necessary, you could consider using object properties for each counter:

var i = 0;
var handles = {};

function counter(tag_name, percent, propname) {
    i++;
    if (i >= percent) clearInterval(handles[propname]);
    if (i <= percent) $(tag_name).html(i + "%");
}
handles.p1 = setInterval(function () {
    counter("#p1", 60, "p1");
}, 50);
handles.p2 = setInterval(function () {
    counter("#p2", 60, "p2");
}, 50);
handles.p3 = setInterval(function () {
    counter("#p3", 60, "p3");
}, 50);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>

This approach works in JavaScript due to the ability to access properties using dot notation with literal property names or brackets notation with string property names.

In conclusion, the first example is generally preferred for this scenario.

Answer №2

To begin with, simply modify == precent to >= precent, then insert the following line underneath

if (i >= precent) clearInterval(varname);
:
if (i >= precent) $(tag_name).html(precent + "%");
. By doing so, the issue will be resolved and the code will function as anticipated.

A demonstration is available on a fiddle located at http://jsfiddle.net/0rukk816/1/

Answer №3

revise this sentence

if (i == precent) clearInterval(varname);

replace it with the following

if (i <= precent) clearInterval(varname);

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: Uncaught TypeError - Unable to assign a value to the 'status' property

Hello everyone, I am currently facing an issue with validating the response from my server using Axios in VueJS. axios.post('/login', { email: this.email, password: this.password }).then(response => { if (response.status == 200) { $ ...

What could be causing bundle.js to remain in a pending status on my website?

Whenever I try to open a page from my project, the browser keeps showing loading forever and in the network tab, the status of bundle.js is pending. (Interestingly, if I open other routes of the project, everything works fine). If I remove all product var ...

Modifying the <TypescriptModuleKind> setting for typescript transpilation in project.csproj is not supported in Visual Studio 2017

I recently encountered an issue with changing the module kind used by the transpiler in Visual Studio. Despite updating the <TypescriptModuleKind> in the project's project.csproj file from commonjs to AMD, the transpiler still defaults to using ...

What is the best way to extract information from a JSON file and display it on a webpage using

I am new to this and I have a question for everyone Here's an example of the JSON response from my URL: The JSON data returned is as follows: { "Data":{ "id": 1312, "Name": "Steem Dollars", "Symbol": "SBD", "website_slug": "steem-dollars", "Level": ...

What significance does the symbol "'" hold in the ng-style attribute?

Can someone explain the purpose of the " \' " in this code snippet? <div ng-style="{ \'cursor\': row.cursor }" Is there a reason why it can't be written simply as <div ng-style="{ cursor: row.cursor }" Here is ...

What is the process for constructing an object to resemble another object?

After collecting input data, I have created an object based on those values. Here is an example of the generated object: var generate_fields = { name: "Mike", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4d9dddf ...

Dynamically load content onto a jQuery Mobile page upon clicking a link

I'm relatively new to working with jQuery Mobile and making AJAX requests. Let me try to explain my issue clearly. Currently, I am developing a mobile project and utilizing the jQuery Mobile auto-complete list, populating it with data from an XML fil ...

Thumbnails gracefully hovering alongside titles

I am puzzled by the fact that some of the thumbnails are displaying differently even though they have the same CSS... h4 { line-height:100%; color: #be2d30; letter-spacing: 1px; text-transform: uppercase; font-family: 'Gnuolane'; font-size:26px ...

The custom event for dynamic page navigation fails to trigger

I have designed a simple button: <button type="button" class="btn btn-success link-accept" data-id="16">Accept</button> along with its corresponding listener: $(document).ready(function() { $('.link-accept').on('click&apo ...

What is the best way to dynamically change the JSON-LD Script for the Schema?

Below is the script in question. Please read through it carefully. <script type="application/ld+json"> { "@context": "http://schema.org/", "@type": "Product", "name": "Bat, &q ...

CSS page rule option for optimal display in Safari

What is the workaround for using alternative rules in Safari? I am currently implementing the angularPrint directive to enable print functionality on certain pages. This directive includes some helper classes in my document and utilizes the @page direct ...

I'm facing an issue with the footer and header that is preventing me from properly positioning any content on the website

When attempting to include an h3 element on the website, it remains stuck at the top. I have tried using CSS properties like position, top, and left but it does not respond to them. Additionally, I experimented with a gallery template from w3schools to see ...

What is the best way to remove column and row gaps in a Bootstrap grid system?

Despite adjusting padding with the image, div section, and grid gap to 0px in the grid layout, the image still fails to cover the entire cell. I am seeking a solution to eliminate these unwanted paddings that are highlighted in blue. The Bootstrap 5 .g-0 ...

Utilizing Python's BeautifulSoup library to extract specific elements from an HTML document

Just getting started with BeautifulSoup and I'm looking to extract specific elements that represent percentages - 98.2% and 94.2%. What I want to print is: apples: 98.2% bananas: 94.2% Any insights on how I can achieve this? Thanks in advance. <d ...

Ways to modify the color of table fonts and contents using inline CSS

I would like some help changing the color of the alphabet in my table. Here is the current format: <table border="1" background="images/haya1.jpg" cellpadding="5" cellspacing="10" width="30%" align="center" bordercolor="brown" bgcolor="red"> & ...

How can one transform an array (in the form of a JSON array) into a map?

After running my script, I receive an array (JSON Array) structured like this: [{redirectCount=0, encodedBodySize=60962, unloadEventEnd=0, responseEnd=1601.699999999255, domainLookupEnd=995.7999999896856, ... Now, I want to display the key-value pairs fr ...

Link several jQuery elements to a function simultaneously

Having 3 jQuery objects is my current situation: var first = $('.el1'); var second = $('.el2'); var third = $('.el3'); I am trying to attach a "change" event to all of them simultaneously, but facing some challenges :( $(fi ...

Working with multi-line HTML content within Javascript

I am currently using JavaScript to define the behavior of a button on a website. I want the button to add new HTML content to a specific part of the page, and I would like to use the MVC extension method Html.EditorFor to create this new HTML. Here is wha ...

Determining when props are updated in Vue.js 2 when passing an object as a prop

Let's say there is an array feedsArray, with a sample value like this: this.feedsArray = [ { id: 1, type: 'Comment', value: 'How are you today ?' }, { id: 2, type: 'Meet', name: 'Daily ...

Encountering a "Page Not Found" error while configuring Passport in Express 4

Struggling with integrating passport into my Node.js application. Despite rearranging my requirements in app.js, I'm unable to resolve the issue. The error message reads: Not Found 404 Error: Not Found at /home/salma/Desktop/my-project/app.js:5 ...