将超时添加到循环

时间:2018-10-24 21:20:29

标签: javascript loops settimeout

我有一个功能,可以在计时器达到5000ms时执行操作:

         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>

2 个答案:

答案 0 :(得分:2)

这是因为它快速循环了5次,然后所有5个循环都在5秒后延迟。超时会在5秒后暂停,而不是提前5秒。

答案 1 :(得分:0)

也许您可以通过这种方式修改代码以实现所需的基于计时器的迭代:

//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();