I'm trying to make a counter that goes up to 100 in 10 seconds and then loops. What is wrong with my code?
window.onload = function () {
var showPercent = window.setInterval(function () {
if (currentPercent < 100) {
currentPercent += 1;
} else {
currentPercent = 0;
}
document.getElementById('result').innerHTML = currentPercent;
}, 100);
};
4 Answers 4
You're not declaring currentPercent anywhere on your code, you should add something like: var currentPercent = 0; before showPercent
2 Comments
var currentPercent = 0;
setInterval(function() {
if (currentPercent < 100) {
currentPercent += 1;
} else {
currentPercent = 0;
}
document.getElementById('result').innerHTML = currentPercent;
}, 100);
Comments
In your fiddle you already had it to run onload. The problem with your snippet is that currentPercent needs to exist outside the setInterval callback scope:
var currentPercent = 0;
var showPercent = window.setInterval(function() {
if (currentPercent < 100) {
++currentPercent;
} else {
currentPercent = 0;
}
document.getElementById('result').innerHTML = currentPercent;
}, 100);
Comments
I got the following error when loading the page in Firefox with Firebug enabled:
ReferenceError: currentPercent is not defined
You're comparing the value stored in variable currentPercent against '100', but the variable hasn't been defined yet. Making a couple of small alterations to the code makes it work just fine:
var currentPercent = 0;
window.onload = function() {
var showPercent = window.setInterval(function() {
if (currentPercent < 100) {
currentPercent += 1;
}
document.getElementById('result').innerHTML = currentPercent;
}, 100);
};
varconsoleand you will seeUncaught ReferenceError: currentPercent is not definedwindow.onloadafter the page was already loaded (the jsFiddle is set up to run the JavaScript "onLoad").no wrap - in <body>in your jsFiddle options.Security Considerationswhen using.innerHTML