У меня есть функция, которая будет выполнять действие, когда таймер достигнет 5000 мс:
var timer = new Timer(function () {
console.log("refreshingBid");
refreshBid();
}, 5000);
timer.pause();
if (isElementInViewport() === true) {
console.log("element in view");
timer.resume();
} else {
timer.pause();
console.log("element is out of view")
}
//I am trying to loop this 5 times with the 5000ms delay - the code I am using for this is:
for (i=0;i<=5;i++)
{
MyFunc();
}
Кажется, что независимо от того, поставил ли цикл цикла в таймер или поставил ли я таймер внутри цикла for, результат будет таким же, где все 5 циклов происходят мгновенно, а не с задержкой таймера, который применяется? Я не уверен, что я делаю неправильно здесь... Любая помощь будет оценена!
Извините, отредактируйте, чтобы включить полный код ниже:
<script>
var iframe2 = document.getElementById('postbid_if');
function isElementInViewport() {
var el = document.getElementById('postbid_if')
console.log(el)
var rect = el.getBoundingClientRect();
console.log(rect)
return rect.bottom >= 0 &&
rect.right >= 0 &&
rect.left < (window.innerWidth || document.documentElement.clientWidth) &&
rect.top < (window.innerHeight || document.documentElement.clientHeight);
}
function Timer(callback, delay) {
var timerId, start, remaining = delay;
this.pause = function () {
window.clearTimeout(timerId);
remaining -= new Date() - start;
};
this.resume = function () {
start = new Date();
window.clearTimeout(timerId);
timerId = window.setTimeout(callback, remaining);
};
this.resume();
}
for (i = 0; i <= 5; i++) {
MyFunc();
}
var timer = new Timer(function () {
console.log("refreshingBid");
refreshBid();
}, 5000);
timer.pause();
if (isElementInViewport() === true) {
console.log("element in view");
timer.resume();
} else {
timer.pause();
console.log("element is out of view")
}
</script>
Возможно, вы могли бы пересмотреть свой код таким образом, чтобы достичь итераций по таймеру по мере необходимости:
//Track the current iteration
var i = 0;
function MyFunc() {
var timer = new Timer(function () {
console.log("refreshingBid");
refreshBid();
// The current timer has completed. If the current
// iteration is less than 5...
if(i < 5) {
i++;
// .. then start another timer for the next iteration
MyFunc();
}
}, 5000);
timer.pause();
if (isElementInViewport() === true) {
console.log("element in view");
timer.resume();
} else {
timer.pause();
console.log("element is out of view")
}
}
// Start the first iteration
MyFunc();
Nested loopbacks
?
Это потому, что он быстро проходит через 5 раз, после чего все 5 петель задерживаются через 5 секунд. Таймаут приостанавливает его через 5 секунд, а не на 5 секунд вперед.
Timer
?