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.