Может кто подсказать? Пишу скрипт, который запускает таймер, когда человек проскроллил экран до определенного блока. Таймер отсчитывает 10 сек. Если в теч. этого времени человек прокрутил этот блок (неважно в каком направлении), то счетчик обнуляется, а если изучал блок все 10 сек., то появляется другой блок. Так вот, собственно, вопрос. С правильной ли стороны я изначально начал подходить к вопросу, и почему не работает clearInterval при выходе с блока ?
// function printNumbers(from, to) {
// let current = from;
// const timerBox = document.querySelector('.timer');
// let timerId = setInterval(function() {
// timerBox.innerHTML = current;
// if (current == to) {
// clearInterval(timerId);
//
// }
// current++;
// }, 1000);
// }
document.addEventListener("DOMContentLoaded", function() {
let counter = 0;
let currentNum = 0;
const timerBox = document.querySelector('.timer');
const element = document.querySelector('.screen3');
const elemHid = document.querySelector('.screen-hidden');
window.addEventListener('scroll', function(){
const elemPosition = {
top: window.pageYOffset + element.getBoundingClientRect().top,
bottom: window.pageYOffset + element.getBoundingClientRect().bottom
}
const windowPosition = {
top: window.pageYOffset,
bottom: window.pageYOffset + document.documentElement.clientHeight
}
if( elemPosition.top < windowPosition.bottom && elemPosition.bottom > windowPosition.top && counter == 0 ){
let timerId = setInterval(function(){
timerBox.innerHTML = currentNum;
if(currentNum == 10){
clearInterval(timerId);
}
currentNum++;
}, 1000);
counter = 1;
}
else {
clearInterval(timerId);
}
});
});
.section{ height: 700px; }
.screen-hidden{display: none;}
.timer{ position: fixed; top: 0; left: 0; display: inline-block; padding: 20px; background: black; color: white; }
<div class="timer">0</div>
<section class="section screen1" style="background-color: red;"></section>
<section class="section screen2" style="background-color: yellow;"></section>
<section class="section screen3" style="background-color: green;"></section>
<section class="section screen-hidden" style="background-color: black;"></section>
<section class="section screen4" style="background-color: blue;"></section>
<section class="section screen5" style="background-color: pink;"></section>