Skip to content
Advertisement

Always calculate var Javascript

I’m trying to show a variable on a html page that should always recalculating itself.

var actualTimeSec = 0; //evolves while the page is loaded
var xTot = 500;        //fixed
var timeTotSec = 60;   //fixed

while(stop === false){
    var x = (actualTimeSec*xTot)/timeTotSec;
    document.querySelector("#xId").innerHTML = x;
}

And in my HTML, I have a div showing the x variable. But when the while loop is working, I can’t click on any other button. How can I always calculate the x variable (until the user closes the page) but still being able to click on other buttons ?

Advertisement

Answer

As ‘Barmar’ said in comments, I should put the content of the loop inside a function and call the function with the setInterval() method. (It would call the function every 10ms for example, without breaking the rest of the page)

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement