Есть много способов решить эту проблему.Многие из них упоминаются в этом вопросе , как упомянуто @EmadZamout в комментариях.
Но, если вы ищете простой и, возможно, альтернативный способ решения этой проблемы.Попробуй это.Здесь я использую requestAnimationFrame
для решения проблемы
let ran = Date.now(); // contains the last updated time
let time = 0; // time in seconds
let paused = false; // store the state
const func = () => {
if (!paused && Date.now() - ran > 1000) {
time++;
ran = Date.now();
console.log('now')
}
if (time === 8)
return alert('This works!');
requestAnimationFrame(func);
}
func();
document.querySelector('button').addEventListener('click', () => paused = !paused);
<button>Change state</button>
Для остановки всех анимаций веб-сайта необходимо вручную остановить каждую анимацию.
Для остановкиjQuery анимацию, вы можете использовать .stop()
помощник.Пример:
let paused = false; // state of the animation
let dir = 'down'; // to store the direction of animation so that the next time continues in the correct direction
let timeDown = 2000; // to animate properly after resuming
let timeUp = 2000; // to animate properly after resuming
// the initial calling of the animation
(function() {
slideDown();
})();
// function which resumes the animation
function animate() {
switch (dir) {
case 'up':
slideUp();
break;
case 'down':
slideDown();
break;
}
}
// a function to animate in the uppward direction
function slideUp() {
dir = 'up'; // setting direction to up
timeDown = 2000; // resetting the duration for slideDown function
$('div').stop().animate({
left: 0
}, {
duration: timeUp,
complete: slideDown, // calling slideDown function on complete
progress: function (animation, progress, ms) {
timeUp = ms; // changing the duration so that it looks smooth when the animation is resumed
}
}); // actual animation
}
// a function to animate in the downward direction
function slideDown() {
dir = 'down'; // setting direction to down
timeUp = 2000; // resetting the duration for slideDown function
$('div').stop().animate({
left: 200
}, {
duration: timeDown,
complete: slideUp, // calling slideUp function on complete
progress: function (animation, progress, ms) {
timeDown = ms; // changing the duration so that it looks smooth when the animation is resumed
}
}); // actual animation
}
// button click event listener
$('button').click(function() {
if (paused)
animate(); // to resume the animation
else
$('div').stop(); // to stop all the animations on the object
paused = !paused; // toggling state
});
div {
position: relative;
width: 100px;
height: 100px;
background: dodgerblue;
}
<button>Pause</button>
<div></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Для начальной загрузки я не думаю, что у вас есть какие-либо анимации начальной загрузки, которые необходимо было приостановить в этом сценарии, о которых вы упомянули, так как анимации начальной загрузки зависятна взаимодействия с пользователем.Если вы хотите предотвратить взаимодействие с пользователем, вы можете наложить на веб-сайт надпись «Приостановлено».Или, если вы не хотите этого делать, вы можете использовать свойство CSS pointer-events: none
, чтобы отключить все события указателя.
Теперь для CSS-анимации вы можете установить свойство с именем animation-play-state
на paused
.
Если вы хотите изменить состояние анимации на паузу, когда пользователя нет на странице (как я понял для ваших обновленных вопросов), вы можете использовать новый visibilityState
API для этого.Событие visibilitychange
вызывается при изменении видимости.
document.addEventListener("visibilitychange", function() {
console.log( document.visibilityState );
document.querySelector('div').innerHTML = document.visibilityState;
});
<div>
Try opening a different tab or change the focus to another app
</div>