Запускать таймер при скролле. javascript
Может кто подсказать? Пишу скрипт, который запускает таймер, когда человек проскроллил экран до определенного блока. Таймер отсчитывает 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>
Ответы (1 шт):
Автор решения: Сергей Комыза
→ Ссылка
Если вдруг кому нужно будет
// таймер начинает работать только когда красный блок находится в зоне вьюпорта, иначе останавливается и сбрасывается в начало
window.addEventListener('load', event => {
let timer;
const timerBox = document.querySelector('.timer');
let currentNum = 10;
const box = document.querySelector('.item');
const boxHidden = document.querySelector('.item-black');
let prevRatio = 0.0;
function countdown(){
timerBox.innerHTML = currentNum;
currentNum--;
if(currentNum < 0){
clearTimeout(timer);
boxHidden.style.display = 'block';
} else{
timer = setTimeout(countdown, 1000);
}
}
let observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
let curRatio = entry.intersectionRatio;
if(curRatio > prevRatio){
entry.target.style.background = `red`;
countdown();
} else{
entry.target.style.background = `transparent`;
clearTimeout(timer);
currentNum = 10;
}
prevRatio = curRatio;
})
}, { threshold: 0.1 });
observer.observe(box);
});
.item {
width: 640px;
height: 480px;
outline: 2px solid;
margin: 100vh auto;
}
.item-black{width: 100px; height: 100px; background: black; display: none; color: #FFF;}
.timer{ position: fixed; top: 0; left: 0; display: inline-block; padding: 20px; background: black; color: white; }
<div class="timer">10</div>
<div class="item">
если долго разглядывать этот блок...
<div class="item-black"> то появляется этот</div>
</div>