Reputation: 69
I am trying to make a dynamic progress bar which starts from 1% width and goes to 100% width; Here is the function
const dynamicBar = (id)=>{
let bar = document.getElementById(id);
let width = 1;
let id= setInterval(frame,10);
function frame(){
if(width>=100){
clearInterval(id);
}
else{
bar.style.width = width + "%";
width++;
}
}
};
And the html part:
<div class="w3-light-grey">
<div class="w3-red" style="width:20%;height:20px;" id="bar1">
</div>
</div>
<button onClick="dynamicBar('bar1')" class="w3-button">Click Me</button>
but the function does not work. It works if i use var instead of let but i want to know how to do this using let keyword.
Upvotes: 1
Views: 301
Reputation: 21
when you are using var, your first Id is been overridden by your second id assignment, so it will not throw an error. but when you use let, it tends to keep the code integrity and says no.
as an example
var foo = "something"
var foo = "another thing"
console.log(foo) //another thing
but
let foo = "something"
let foo = "another thing"
give you this, "Identifier 'foo' has already been declared"
one more thing, is that use const for constant values.
instead of this
let id = setInterval(frame, 10);
use
const interval = = setInterval(frame, 10);
make sure you clear interval inside fame
clearInterval(interval)
and your code will start working
Upvotes: 1
Reputation: 3512
let
doesn't allow you to define something twice, so you need to use a different name. You had id
for both your parameter and in line 5, which isn't allowed with let
.
For example,
let var1 = true;
let var1 = false;
would throw an error, since it defines var1 twice. However, you can change the value.
let var1 = true;
var1 = false;
The code block above would work just fine. let
is used so that you don't accidentally override a variable in a big program.
const dynamicBar = (idName) => {
let bar = document.getElementById(idName);
let width = 1;
let id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
bar.style.width = width + "%";
width++;
}
}
};
<div class="w3-light-grey">
<div class="w3-red" style="width:20%;height:20px;background-color:red;" id="bar1">
</div>
</div>
<button onClick="dynamicBar('bar1')" class="w3-button">Click Me</button>
Upvotes: 3