简体   繁体   中英

Can i make a number appear on my page then have it increase by x every z seconds

Take this number "#1" Make it turn to a "#2" in 5 seconds Then to a "#3" in 5 seconds

Is this possible, or how do i accomplish this?

Because PHP executes on the server and only sends the resulting output to the browser, we can't use only PHP to update it.

Easiest method would be to use JavaScript's setTimeout method.

function update() {
  var counter = document.getElementById("counter");
  counter.innerText = counter.innerText*1 + 1;
  setTimeout(update, 1000);
} 

<body onload="update()">
  <div id="counter">0</div>
</body>

The update function gets called once on the body's load and then it calls itself after 1000ms to make a 1 second counter. Note: I have to multiply the innerText by 1 to convert a string to a number so it will add instead of concatenating.

Another way of doing this, although I don't know why you'd want to do it this way (but it uses PHP.. lol) is to refresh the page with an updated query string parameter.

<?PHP
$newcount = 0;
if(isset($_GET['count'])) {
    $newcount = $_GET['count'] + 1;
    echo $newcount;
}

echo "<meta http-equiv='refresh' content=\"1;URL='a.php?count={$newcount}'\">";
?>

Here I get the current value of the counter and add 1 using PHP and then echo a meta refresh tag to, after 1 second, refresh the page with the updated count value in the query string. Next time the page loads, it'll read that value, add one, refresh with the new value, etc. This is just to show you another way, I would not recommend doing this in your application!

You might want to use this shell script: How to Run Cron Every 5 Minutes, Seconds, Hours, Days, Months

Cron job cannot be used to schedule a job in seconds interval, so you need a custom script to exec from your php code.

Then your php code would be like that:

$x = 1; 
$z = 5;

file_write_contents("file.txt", $x + file_get_contents("file.txt"););

echo file_get_contents("file.txt");

Also you would need to modify your bash script according to $z.

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