+ 2
Inner variable counting?
My main objective is to make a variable that increments by 1 in a specific time.this is what i got so far: var a = 0; function inc (){ var b; b=a++; document.write(b) } setInterval ( inc , 1000) I want to make it stay in one place. this just goes endless in a direction, I don't know how make it stay and don't go with counting to right forever.
6 Answers
+ 4
Sorry. I understand now. It's because you're writing it to the document each time.
https://code.sololearn.com/WbEG1BasNvDq/#js
^Give that a shot. I think it's what you're looking for. Just create a counter DIV in the HTML so you can update it with the new time each interval.
HTML:
<div id="counterDiv"></div>
JS:
var a = 0;
function inc (){
var b;
b=a++;
document.getElementById("counterDiv").textContent = b;
}
setInterval ( inc , 1000)
+ 8
This is what I came up with a little search around on how to get the stuff done. I have never done JS before. It's probably not the "correct" way, but thought I should just share it anyways.
var a = 0;
function inc (){
var b;
b=a++;
document.body.innerHTML = "";
document.write("a = " + b + "<br>")
}
setInterval ( inc , 1000)
+ 4
You're welcome Olm.
Although it's better to utilize the elements you created (such as a DIV) instead of manipulating the entire document, Hatsy made an excellent point by showing you how to clear out the document's body by giving it an empty string value before appending the new data. It's not ideal for most practical uses, but it's always good to know all of the various ways to go about your problem.
To clarify my point, imagine that you have a bunch of other unrelated stuff inside of the document's body. If you go about it that way, you'll clear out everything else also. If you keep it isolated to your DIV, then it'll only affect that element while leaving everything else alone.
+ 3
As Taco mentioned, "document.write(b)" just appends it and doesn't remove anything that you previously added. It's better to utilize the HTML elements to display stuff, rather than manipulating the page via document.write.
+ 1
thanks!
0
I want it to behave like a timer/clock. what it does is "12345". I want a = 1 and when a second pass a = 2 then a = 3 and so on.I don't know how to assign that counting to a variable