-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?

Gustavo
  • 29
  • 5

1 Answers1

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);
        }
    }
};
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thank you, this works! My problem now is that the array, which is displayed in another component, does not refresh. Any idea? – Gustavo Sep 08 '21 at 09:02
  • @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](https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-react-js). – T.J. Crowder Sep 08 '21 at 09:13