I have a simple javascript loop on my php page that just adds 1 to a value every second. Well, the loop runs every second, and increments the value.
var test = 0;
function go() {
test = test + 1;
setTimeout(go, 1000);
}
go();
This works fine.
Problem is, the PHP page this runs on is actually inside a div tag that refreshes every 10 seconds. After 10 seconds, the count goes haywire, adding 2 every second, then 3, then 4, etc.
How can I stop this?
Given that the problem appears to be multiple instances of your function running, increasing on each refresh/update of the page, I’d suggest adding a sanity-check to your function:
As it’s probable that
testis going to be overwritten every time the page updates, I’d suggest ensuring that the assignation isn’t going to overwrite a pre-existing count:Bear in mind that you could simply use the existence of the
testvariable to determine whether the function is currently running or not, but because I don’t know if you’ll be using that for other purposes I’ve chosen to create another variable for that purpose (which should hold eithertrueorfalseBoolean values).