1
I would like to perform a function infinitely every second, I am trying this way but the function is only executed once:
Between the tag body
<div id="map"><div id="seg"></div></div>
<?php
date_default_timezone_set('America/Sao_Paulo');
$Sh = date('G');
$sM = date('i');
$sS = date('s');
$rS = ($Sh*60*60)+($sM*60)+$sS;
?>
Enter the script tag
var myVar = setInterval(function(){ mudarHora() }, 1000);
var tServ = <?php echo $rS; ?> + 3;
function mudarHora() {
var dt = new Date();
var secs = dt.getSeconds() + (60 * (dt.getMinutes() + (60 * dt.getHours())));
var difT = tServ - secs;
var segundosAgora = secs + difT;
document.getElementById("seg").innerHTML = segundosAgora;
}
As I said the function is executed only once and I do not know where the error is.
The function is correct. The error is in the calculation. The variable
segundosAgora
at all times will have the same value.– Valdeir Psr
@valdeirpsr when I refresh the page manually the value of secondsNow changes, why says it will always have the same value?
– talnun
If you add a
console.log( segundosAgora );
within the functionmudarHora
, you will see (F12) that the value will always be the same, despite the function is working. Demonstration: https://codepen.io/valdeir2000/pen/rJpvdr– Valdeir Psr
@valdeirpsr in codepen is not possible to work with php (think) and you set const tServ = 65438; where 65438 is actually a dynamic number (current second of the day - server side). Since the value of tServ is fixed in your example, this is why the latter is always the same now, no?
– talnun
@talnum he’s talking about his calculation of
segundosAgora
, that makes no sense.tServ - secs + secs = tServ
, at all times.– bfavaretto
@talnun This value is fixed. O PHP does not work with client-side dynamic values (except when refreshing the page). As long as you keep the page open, the value does not change. For the variable value
tServ
be changed (without refresh), you should do this with Javascript.– Valdeir Psr
@Valdeirpsr the intention was this, I think: https://codepen.io/anon/XZVqPx?editors=1111
– bfavaretto
It was easier to say what is the desired result. setInterval is working normally.
– Sam