Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
?>
like image 220
Jacob Avatar asked Jan 07 '17 22:01

Jacob


People also ask

Why setTimeout is not working in JS?

If you are requiring the setTimeout functions to execute on the dot, there can be some scenarios when this is not the case. Late timeouts or timeouts that execute inaccurately could be due the following issues: browser or OS is busy with other tasks.

Does setTimeout stop?

No, setTimeout does not wait for you (hence, JS has no pause function). What setTimeout does is set aside that task at a later time, and allow the next line to be executed.

What is alternative to setTimeout?

The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.


1 Answers

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);
}
like image 85
hairmot Avatar answered Sep 19 '22 21:09

hairmot