Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript increment not working

Well I did not know what exactly would be a good title for this because it is a most peculiar situation or I'm abnormally dumb.

Here's what im trying to do.

Create a simple <meter> tag which is new in HTML5. The main issue is with my javascript. Im trying to increment the value of the meter tag gradually in my javascript. But somehow it doesn't work the way i want.

JavaScript.

for (var i = 0; i <= 10; i++) {
    var a = document.getElementById("mtr1");
    setTimeout(function () {
        console.log(i);
        a.value = i;
    }, 250);
}

I'm trying to increase the value of the meter gradually every 250 ms.This doesn't happen. Instead the meter jumps straight to 10.

What interested me was the value of i that i got in the console. I got instances of 10, instead of 1,2,3...10.

Why does this happen?

FIDDLE

like image 978
MarsOne Avatar asked Nov 06 '13 13:11

MarsOne


People also ask

Why ++ is not used in JavaScript?

The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. There is a plusplus option that prohibits the use of these operators.

How do you use +1 in JavaScript?

JavaScript has an even more succinct syntax to increment a number by 1. The increment operator ( ++ ) increments its operand by 1 ; that is, it adds 1 to the existing value. There's a corresponding decrement operator ( -- ) that decrements a variable's value by 1 .

How does ++ work in JavaScript?

Description. If used postfix, with operator after operand (for example, x++ ), the increment operator increments and returns the value before incrementing. If used prefix, with operator before operand (for example, ++x ), the increment operator increments and returns the value after incrementing.

What is the difference between i ++ and ++ i in JavaScript?

++i returns the value of i after it has been incremented. i++ returns the value of i before incrementing. When the ++ comes before its operand it is called the "pre-increment" operator, and when it comes after it is called the "post-increment" operator.


Video Answer


1 Answers

It's a JavaScript closures' classic. Here i is an actual reference to the variable, not its copy. After you've iterated through the loop it has the value of 10, that's why all log invocations write 10 to log.
This should work better:

for (var i = 0; i <= 10; i++) {
    var a = document.getElementById("mtr1");
    setTimeout(function (i) {
        return function() {
            console.log(i);
            a.value = i;
        };
    }(i), 250 * i);
}

Here the most inner i is the setTimeout's callback argument, not the variable which you've declared in the loop body.

like image 121
aga Avatar answered Sep 28 '22 17:09

aga