我有一个函数,它会在计时器达到 5000 毫秒时执行一个 Action :
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 循环放在计时器中还是将计时器放在 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>
最佳答案
这是因为它快速循环了 5 次,然后所有 5 次循环都在 5 秒后延迟。超时会在 5 秒后暂停,而不是预先暂停 5 秒。
关于javascript - 将超时添加到循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52978058/