简体   繁体   English

javascript循环变得令人沮丧

[英]javascript loop going mental

I have a simple javascript loop on my php page that just adds 1 to a value every second. 我的php页面上有一个简单的javascript循环,每秒仅将1添加到一个值。 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. 问题是,运行它的PHP页面实际上位于div标签中,该标签每10秒刷新一次。 After 10 seconds, the count goes haywire, adding 2 every second, then 3, then 4, etc. 10秒后,计数开始增加,每秒增加2,然后增加3,然后增加4,依此类推。

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: 由于每次页面更新时都可能会覆盖test ,因此建议您确保分配不会覆盖现有计数:

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). 请记住,您可以简单地使用test变量的存在来确定该函数当前是否正在运行,但是由于我不知道您是否会将其用于其他目的,因此我选择创建另一个变量为此目的(应包含truefalse布尔值)。

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

You'll also have to mend your test variable. 您还必须修补test变量。 So var test = test || 0; 所以var test = test || 0; var test = test || 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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