Добавление таймаута в цикл

1

У меня есть функция, которая будет выполнять действие, когда таймер достигнет 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>
  • 0
    Вам не хватает кода, пожалуйста, добавьте его.
  • 0
    Что такое Timer ?
Показать ещё 1 комментарий
Теги:
loops
settimeout

2 ответа

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();
  • 0
    Так работает JavaScript с его ожиданием / асинхронностью ... Как это называется? Nested loopbacks ?
  • 0
    Да, здесь можно использовать async / await, чтобы сделать решение немного более элегантным.
Показать ещё 2 комментария
2

Это потому, что он быстро проходит через 5 раз, после чего все 5 петель задерживаются через 5 секунд. Таймаут приостанавливает его через 5 секунд, а не на 5 секунд вперед.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню