简体   繁体   中英

javascript loop going mental

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:

var test = 0;
var running = running || false;

function go() {
    if (running) {
        // if an instance of go() is already running, the function quits
        return false;
    }
    else {
        running = true; // as the test variable survives I assume this will, too
        test = test + 1;
        setTimeout(go, 1000);
    }
  }

go();

As it's probable that test is 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:

var test = test || 0;
var running = running || false;

function go() {
    if (running) {
        // if an instance of go() is already running, the function quits
        return false;
    }
    else {
        var running = true; // as the test variable survives I assume this will, too
        test = test + 1;
        setTimeout(go, 1000);
    }
  }

go();

Bear in mind that you could simply use the existence of the test variable 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 either true or false Boolean values).

Change: go() to if(!test){ go() }

You'll also have to mend your test variable. So var test = test || 0; var test = test || 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM