Как ограничить нажатия в определенное время JS
Есть кнопка переключения блоков, и есть эффект перехода. И мне нужно чтобы нельзя было нажимать на эту кнопку пока не пройдет некоторое время после нажатия. Иначе появляются ненужные визуальные баги. И кнопок 2, одно назад (prev), другое вперед (next)
next.addEventListener('click', function() {
var activeBlock = document.querySelector('.content > .block.active');
var nextBlock = activeBlock.nextElementSibling;
if (nextBlock.classList.contains('block')) {
nextBlock.classList.add('active', 'fadeIn');
nextBlock.style.display = 'flex';
setTimeout(function () {
nextBlock.classList.remove('fadeIn');
nextBlock.style.opacity = '1';
}, 500);
}
else {
firstBlock.classList.add('active', 'fadeIn');
firstBlock.style.display = 'flex';
setTimeout(function () {
firstBlock.classList.remove('fadeIn');
firstBlock.style.opacity = '1';
}, 500);
}
activeBlock.classList.add('fadeOut');
setTimeout(function () {
activeBlock.classList.remove('fadeOut');
activeBlock.classList.remove('active');
activeBlock.style.opacity = '0';
activeBlock.style.display = 'none';
}, 500);
});
Ответы (2 шт):
Автор решения: Igor
→ Ссылка
var timer = null;
next.addEventListener('click', function() {
if (timer)
return;
...
timer = setTimeout(function () {
timer = null;
activeBlock.classList.remove('fadeOut');
activeBlock.classList.remove('active');
activeBlock.style.opacity = '0';
activeBlock.style.display = 'none';
}, 500);
});
Автор решения: Sergey Danyleiko
→ Ссылка
let isDisabled = false;
next.addEventListener('click', function(e) {
if(isDisabled) {
return;
}
isDisabled = true;
var activeBlock = document.querySelector('.content > .block.active');
var nextBlock = activeBlock.nextElementSibling;
if (nextBlock.classList.contains('block')) {
nextBlock.classList.add('active', 'fadeIn');
nextBlock.style.display = 'flex';
setTimeout(function () {
nextBlock.classList.remove('fadeIn');
nextBlock.style.opacity = '1';
isDisabled = false;
}, 500);
}
else {
firstBlock.classList.add('active', 'fadeIn');
firstBlock.style.display = 'flex';
setTimeout(function () {
firstBlock.classList.remove('fadeIn');
firstBlock.style.opacity = '1';
isDisabled = false;
}, 500);
}
activeBlock.classList.add('fadeOut');
setTimeout(function () {
activeBlock.classList.remove('fadeOut');
activeBlock.classList.remove('active');
activeBlock.style.opacity = '0';
activeBlock.style.display = 'none';
isDisabled = false;
}, 500);
});