Jac*_*cob 5 html javascript php settimeout
我有一个页面,我希望始终保持文件中的值.
基本上我有一个脚本保存一些数据供我在网站上以txt文件显示,然后我想在网上显示这些数据.文本文件中的数据每20秒左右更新一次.
它的工作效果很好,比如3分钟左右,然后页面就停止了.任何想法为什么会这样?
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;
?>
Run Code Online (Sandbox Code Playgroud)
一旦调用setTimeout函数,就会立即调用keepRunning方法.这意味着而不是像你可能想要的那样每秒调用它,它被不断地调用(每秒数千次) - 你将很快遇到内存问题,一切都将停止工作.
要解决此问题,请在updatePots函数的末尾调用keepRunning:
function updatePots()
{
updatepot("pot0");
keeprunning();
}
function keeprunning()
{
setTimeout(updatePots, 1000);
}
Run Code Online (Sandbox Code Playgroud)
如果您希望某个函数定期运行,请使用setInterval而不是setTimeout-这样,您不必处理重置时间间隔的问题:
function updatepots()
{
updatepot("pot0");
}
window.setInterval(updatePots, 1000);
Run Code Online (Sandbox Code Playgroud)