Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Остановка таймера (https://javascript.ru/forum/misc/80030-ostanovka-tajjmera.html)

MOT 19.04.2020 19:54

Остановка таймера
 
Здравствуйте! Пишу мини-игру, хочу выяснить один вопрос, но для начала покажу код:
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: cursive;
}
#stop {
display: none;
}
.square1, .square2 {
width: 100px;
height: 100px;
background: red;
position: fixed;
}
.square1 {
top: 100px;
animation: s1 linear infinite 7s;
z-index: 1;
}
.square2 {
top: 200px;
animation: s2 linear infinite 7s;
}
@keyframes s1 {
0% {
left: 0px;
}
50% {
left: calc( 100% - 100px );
}
100% {
left: 0px;
}
}
@keyframes s2 {
0% {
right: 0px;
}
50% {
right: calc( 100% - 100px );
}
100% {
right: 0px;
}
}
label {
border: 1px solid black;
border-radius: 3px;
}
.modalbox {
width: 300px;
height: 300px;
border: 1px solid black;
background: lightgrey;
z-index: 2;
position: fixed;
border-radius: 50px 50px 50px 50px / 10px 10px 10px 10px;
left: calc( 50% - 150px );
top: calc( 50% - 150px );
}
.ml {
width: 200px;
height: 40px;
text-align: center;
border: 1px solid black;
border-radius: 10px 10px 10px 10px / 30px 30px 30px 30px;
position: absolute;
left: calc( 50% - 100px );
top: calc( 50% - 20px );
}
#stop ~ .modalbox {
opacity: 0;
}
#stop:checked ~ .modalbox {
opacity: 1;
}
#stop ~ * {
animation-play-state: running;
transition: 0.5s;
}
#stop:checked ~ * {
animation-play-state: paused;
transition: 0.5s;
}
</style>
<script>
function init()
            {
                sec = 0;
                setInterval(tick, 1000);
            }
            
            function tick()
            {
                sec++;
                document.getElementById("timer").
                    childNodes[0].nodeValue = sec;
}
</script>
</head>
<body onload="init()">
<input type="checkbox" id="stop"><br>
<div class="timer_wrapper"><span id="timer">0</span> сек идёт игра</div>
<label for="stop">Стоп</label>
<div class="square1"></div>
<div class="square2"></div>
<div class="modalbox">
<label for="stop"><div class="ml">Продолжить игру</div></label>
</div>
<script>
document.getElementById("stop").checked = false;
</script>
</body>
</html>

Как видно, при нажатии на кнопку "Стоп" происходит остановка анимации блоков, но при этом таймер не останоавливается. Попытался прикрутить функцию типа if (stop.checked = true) {...}, но не прижилось. Не могли бы вы мне помочь остановить таймер? Вопрос простецкий, конечно, но реализовать не получилось :-?

voraa 19.04.2020 20:05

let timer = setInterval (fun, time) // Запустить таймер
clearInterval(timer) // Остановить таймер

А вообще setInterval (fun, time) - запускать функцию fun не раньше, чем через time ms. Может быть и позже. Поэтому отсчитывать по ней время не стоит. Со временем накопится ошибка.
Лучше так

let t0;
function init()
            {
                t0 = new Date().getTime();
                setInterval(tick, 1000);
            }
             
            function tick()
            {
                let sec = ((new Date().getTime() - t0)/1000 +0.5) | 0;
                document.getElementById("timer").
                    childNodes[0].nodeValue = sec;
}

рони 19.04.2020 20:07

Цитата:

Сообщение от MOT
if (stop.checked = true) {...}, но не прижилось.

исправьте и сработает

MOT 19.04.2020 22:33

Исправил:
<!DOCTYPE html>
<html>
<head>
<script>
    function init()
            {
                sec = 0;
                setInterval(tick, 10);
            }
            
            function tick()
            {
                sec++;
                document.getElementById("timer").
                    childNodes[0].nodeValue = sec;
            }
function check() {
    if (document.getElementById('stop').checked) {
        clearInterval(timer);
    }
}
        </script>
</head>
<body onload="init()">
<input type="checkbox" id="stop"/><label for="stop" onclick="check()">Включить</label>
<div id="timer"></div>
</body>
</html>

Не работает с setInterval, даже если поставить тот же alert, всё "фурычит". В чём ошибка?

рони 19.04.2020 22:36

MOT,
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: cursive;
}
#stop {
display: none;
}
.square1, .square2 {
width: 100px;
height: 100px;
background: red;
position: fixed;
}
.square1 {
top: 100px;
animation: s1 linear infinite 7s;
z-index: 1;
}
.square2 {
top: 200px;
animation: s2 linear infinite 7s;
}
@keyframes s1 {
0% {
left: 0px;
}
50% {
left: calc( 100% - 100px );
}
100% {
left: 0px;
}
}
@keyframes s2 {
0% {
right: 0px;
}
50% {
right: calc( 100% - 100px );
}
100% {
right: 0px;
}
}
label {
border: 1px solid black;
border-radius: 3px;
}
.modalbox {
width: 300px;
height: 300px;
border: 1px solid black;
background: lightgrey;
z-index: 2;
position: fixed;
border-radius: 50px 50px 50px 50px / 10px 10px 10px 10px;
left: calc( 50% - 150px );
top: calc( 50% - 150px );
}
.ml {
width: 200px;
height: 40px;
text-align: center;
border: 1px solid black;
border-radius: 10px 10px 10px 10px / 30px 30px 30px 30px;
position: absolute;
left: calc( 50% - 100px );
top: calc( 50% - 20px );
}
#stop ~ .modalbox {
opacity: 0;
}
#stop:checked ~ .modalbox {
opacity: 1;
}
#stop ~ * {
animation-play-state: running;
transition: 0.5s;
}
#stop:checked ~ * {
animation-play-state: paused;
transition: 0.5s;
}
</style>
<script>
 function init()
 {
   sec = 0;
   setInterval(tick, 1000);
 }
 function tick()
 {
   if(document.getElementById("stop").checked) return;
   sec++;
   document.getElementById("timer").textContent = sec;
 }
</script>
</head>
<body onload="init()">
<input type="checkbox" id="stop"><br>
<div class="timer_wrapper"><span id="timer">0</span> сек идёт игра</div>
<label for="stop">Стоп</label>
<div class="square1"></div>
<div class="square2"></div>
<div class="modalbox">
<label for="stop"><div class="ml">Продолжить игру</div></label>
</div>
<script> document.getElementById("stop").checked = false;</script>
</body>
</html>

voraa 19.04.2020 22:56

Цитата:

Сообщение от MOT (Сообщение 523071)
Не работает с setInterval, даже если поставить тот же alert, всё "фурычит". В чём ошибка?

Не внимательно посмотрели мой пост

<!DOCTYPE html>
<html>
<head>
<script>
   let timer;
    function init()
            {
                sec = 0;
                timer = setInterval(tick, 10);
            }
            
            function tick()
            {
                sec++;
                document.getElementById("timer").innerHTML = sec
            }
function check() {
    if (document.getElementById('stop').checked) {
        clearInterval(timer);
    }
}
        </script>
</head>
<body onload="init()">
<input type="checkbox" id="stop"/><label for="stop" onclick="check()">Включить</label>
<div id="timer"></div>
</body>
</html>


Часовой пояс GMT +3, время: 14:08.