简体   繁体   中英

setTimeout stops working

I have a page where I want to keep a value from a file uppdated all the time.

Basicly I have a script saving some data for me to show on the web in a txt file and then I want to show this data on the web. The data in the text file will update every 20 sec or so.

It works good the first like 3 min or so then the page stops uppdating. Any ideas why this is happening?

function updatepot(elementid) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById(elementid).innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET", "../readData.php?q=" + elementid, true);
        xmlhttp.send();

}

function updatePots()
{
       updatepot("pot0");
}
function keeprunning()
{
    setTimeout(updatePots, 1000);
    keeprunning();
}


<?php    
// get the q parameter from URL
$file = $_REQUEST["q"] . ".txt";
$myfile = fopen("potData/".$file, "r") or die("Unable to open file!");
$myData;
while(!feof($myfile)) {
  $myData =  $myData . fgets($myfile);
}
fclose($myfile);
echo $myData;
?>

Your keepRunning method is being called immediately as soon as the setTimeout function is called. This means rather than it being called every second as you probably intend, it is being called constantly (thousands of times a second) - you will quickly run into memory problems and everything will stop working.

To fix this, call keepRunning at the end of your updatePots function:

function updatePots()
{
       updatepot("pot0");
       keeprunning();
}
function keeprunning()
{
    setTimeout(updatePots, 1000);
}

If you want a function to run periodically, use setInterval instead of setTimeout -- this way, you don't have to deal with resetting the interval:

function updatepots()
{
    updatepot("pot0");
}

window.setInterval(updatePots, 1000);

call it in this way:

function updatePots()
{
    updatepot("pot0");
    keeprunning();
    setTimeout(updatePots, 1000);
}

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