0

I have this function:

getKeyboardStartingPoint() {
    let currentCellNumberElement;

    window.setTimeout(function() {
        $cells.each(function() {
            currentCellNumberElement = $(this).find('[data-number]');
            if (currentCellNumberElement.text().trim().length === 0) {
                currentCellNumberElement.css('background-color', 'orange');
                return false;
            }
        });
    }, 100);

    return currentCellNumberElement;
}

The variable currentCellNumberElement is declared locally within the function at the top, processed in the each loop and after that I try to alert it. However, the variable returns undefined. The css changes on the element works, so the variable does have a value, but for some reason it becomes undefined when the each loop ends. What's the issue here?

erol_smsr
  • 1,454
  • 4
  • 24
  • 49
  • I think the basic issue might be that the return false is returning from the setTimeout, so it ends up nowhere, also there is no else condition so the function will return false or undefined. Furthermore the alert is occurring before the setTimeout has completed, so will always be undefined. – user3094755 Apr 12 '17 at 11:06
  • 1
    @user3094755 return false stops the `$.each` loop, so that part is fine. – JJJ Apr 12 '17 at 11:07
  • Returning the variable inside the timeout doesn't work as well (undefined). Alerting or console logging the variable inside the timeout does work. However, I need to return it. – erol_smsr Apr 12 '17 at 11:10
  • You can't. The function ends long before the timeout resolves. – JJJ Apr 12 '17 at 11:11

1 Answers1

1

You print currentCellNumberElement before you get into your loop where it is assigned a value.

I think you ment to do this:

getKeyboardStartingPoint() {
    let currentCellNumberElement;

    window.setTimeout(function() {
        $cells.each(function() {
            currentCellNumberElement = $(this).find('[data-number]');
            if (currentCellNumberElement.text().trim().length === 0) {
                currentCellNumberElement.css('background-color', 'orange');
                return false;
            }
        });
        alert(currentCellNumberElement);
    }, 100);

}

But like JJJ said: full explanation here: Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Community
  • 1
  • 1
Wannes Van Dorpe
  • 822
  • 6
  • 17
  • Thanks, I just figured this out. However, I made the mistake of asking this question with alert. Actually, I need to return it, however when I return the variable inside the timeout it returns undefined as well. – erol_smsr Apr 12 '17 at 11:12
  • 1
    I think this answer covers your question pretty well: http://stackoverflow.com/questions/19986444/return-variable-after-settimeout – Wannes Van Dorpe Apr 12 '17 at 11:14