-1

I have a function "fill" which fills an array with numbers, and I want to do it as long as this array has empty values. But it want a delay of one second for each number.

I found here on stackoverflow a solution for how to use setTimeOut with loop, but my problem is different, as the loop will break depending on a boolean. This is what I got so far, using the same idea:

  var fillCache = function () {
        var i = state.cache.indexOf("")
        while (i !== -1) {
            (function (i) {
                setTimeout(function () { fill }, 1000)
            })
            i = state.cache.indexOf("")
        }
    }

What I get is an error saying "expected an assignment or function call and instead saw an expression" for Line 4. Any idea? Or am I completely wrong?

2
  • What is fill? It's not defined anywhere. Commented Sep 8, 2021 at 8:45
  • 1
    Other issues aside, your loop is going to block the event loop so no other JS will run so state.cache will never change, so the loop will never end. Commented Sep 8, 2021 at 8:47

1 Answer 1

1

There are three problems there:

  1. while is a synchronous operation, but you have an asynchronous operation that you want to repeat until a specific condition is met, so while isn't the right choice. In fact, as Quentin points out, it will prevent the condition from becoming true because, since it's synchronous and never-ending, it never lets anything else happen.

  2. You never call the inline-invoked function expression in the loop.

  3. In the setTimeout callback, you never call fill, you just refer to it, which (in this case) doesn't do anything.

You probably want a setTimeout that calls itself, something like this:

const fillCache = function () {
    // When called, start the process
    tick();

    // Handles each tick
    function tick() {
        // Is the condition true?
        if (state.cache.indexOf("") !== -1) {
            // Not yet, call `fill`...
            fill();
            // ...and go again in a second
            setTimeout(tick, 1000);
        }
    }
};
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this works! My problem now is that the array, which is displayed in another component, does not refresh. Any idea?
@Gustavo - Sounds like you're not storing the array in state / providing it as a prop, or you are doing one of those things but not updating it correctly. If it's an update issue, see this question's answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.