'How to prevent re-called-ajaxpages of stacking javascript setIntervals?
I am using a master-page with a few ajax-elements. One of the elements does a timer-countup.
The problem is: If I am leaving the ajaxsubpage to another ajaxsubpage and THEN go back, the timer is executed twice. Means: A new timer starts at 00:00:00 - and the old timer from the previous visit continues to run.
How can I prevent this behavior?
[ajaxsubpage.php] [...]
<div id ="vorgang_countup">00:00:00</div>
<?php
$vorgang_start = new DateTime("now", new DateTimeZone('Europe/Berlin'));
$_SESSION['vorgang_start'] = $vorgang_start;
?>
[...]
<script>
let interval_var;
function padDigits(number, digits) {
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}
function countup (InitialTime) {
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
let jsinitial = new Date(InitialTime);
interval_var = setInterval(function() {
let now = new Date();
distance = now-jsinitial;
document.getElementById("vorgang_countup").innerText = padDigits(Math.floor((distance % (day)) / (hour)),2) + ":" + padDigits(Math.floor((distance % (hour)) / (minute)),2) + ":" + padDigits(Math.floor((distance % (minute)) / second),2);
}, 1000);
}
clearInterval(interval_var);
countup('<?php echo $_SESSION['starttime']->format('c'); ?>');
<script>
The clearInterval-function does not seem to work this way. Everytime the ajaxsubpage is loaded and fittet into the mainpage additional instance of the funtion countup is running.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
