setInterval does not work correctly

1

I would like to execute a function infinitely every second, I am trying this way but the function is only executed once:

Enter the body tag

    <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.

    
asked by anonymous 17.02.2018 / 20:45

1 answer

1

Edited

So the difficulty is to restart the function by TIMER in javascript? If you try to use setTimeout :

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;
   setTimeout(function(){ mudarHora() }, 1000);
}

To trigger the function use the event onload like this:

<body onload="mudarHora()">

This will be the complete code:

<?php
date_default_timezone_set('America/Sao_Paulo');
$Sh = date('G');
$sM = date('i');
$sS = date('s');
$rS = ($Sh*60*60)+($sM*60)+$sS;
?>
<!DOCTYPE html>
<html>
<head>
<script>
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;
   setTimeout(function(){ mudarHora() }, 1000);
}
</script>
</head>
<body onload="mudarHora()">
<div id="map"><div id="seg"></div></div>
</body>
</html>
    
17.02.2018 / 23:10