arii arii - 1 month ago 10
Javascript Question

display current value of var to HTML

I have a variable

speed
controlled by the user from keyboard, and I want to display it current value all the time.

I tried:

var user_speed= 1; //init

<h3 style="float:left;" id="userspeed"></h3>

document.getElementById("userspeed").innerHTML = user_speed.toFixed(2);


but what I get is only
speed = 1
and it never changed.

Is there a way to keep changing the displayed value, without creating a function that fire each time the user change the speed and execute
document.getElementById()...
again?

Answer

Why not use setInterval to update the value like so:

var speed = 1; //init

setInterval(function(){
   document.getElementById("userspeed").innerHTML = user_speed.toFixed(2);
}, 1000);

This will update the value every 1 second (1000 ms).