Search code examples
reactjsloopssettimeout

setTimeout() method inside a while loop with boolean break


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?


Solution

  • 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);
            }
        }
    };