javascript - 将超时添加到循环

标签 javascript loops settimeout

我有一个函数,它会在计时器达到 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/

相关文章:

javascript - 如何使用google api减少折线图中haxis和注释值之间的差距

java - 查找数组 Java 中最后一次出现的位置?

php - 没有浏览器的循环php脚本

Angular 4 setTimeout不等待

javascript - Ajax 轮询 - 高效吗?

javascript - 如何每 5 秒运行一个函数,每次都有不同的值?

javascript - 使用 JavaScript 查找图像的高度 - 图像加载错误

javascript - 对 JavaScript 超时感到困惑

javascript - 以编程方式创建表单无法在 Firefox 或 Internet Explorer 中提交

java - 用 Java 编写一个程序来估计 PI (π) 使用 Leibniz 级数