Good day.
Faced the concept of closure in jQuery for the first time and can't get around it.
The closure occurs in the reward function:
$(document).ready(function () { var messages = [ "Nice Job!", "Excellent clickin'!", "That was Awesome!", "Man are you good!", "Boom!", "You're a pro!", "Unbelievable!", "Insanity!", "You're on fire!", "That was crazy!", "You are blowin' my mind!" ] var levels = 0; reward = function() { $('.ball-container').css('display','none'); $('.message_container').css('position', 'relative'); for(levels = 0; levels <= messages.length; levels++){ $('#text').css('visibility','visible').html(messages[levels]); $('#next_level').css('visibility','visible').html('Next Level: ' + levels); } window.setTimeout(hideText, 2000) }; hideText = function() { $('.message_container').css('position', 'absolute'); $('#text').css('visibility','hidden'); $('#next_level').css('visibility','hidden'); $('.ball-container').css('display','block'); $('.ball').click(reward); }; $('.ball').click(reward); }); The reward function is called when clicking on a certain shape on the page. All solutions found on the network did not work.
Thank.
Update
The problem is that with this code, the levels always equals 11 (that is, the maximum value of messages.length). And there should be an iteration with a value from 0 to 11. The reason for this behavior of the code is in the closure of JS / Jquery. I tried to rewrite the code so that the iteration I needed was, but it does not change.
Update
@Zelta , thanks for the clarification. In general, it worked this way.
$(document).ready(function (){ var messages = [ "Nice Job!", "Excellent clickin'!", "That was Awesome!" ] var levels = 0; $('.ball').click(function(){ if(levels <11){ flashMessage(); flashMessage = function() { var message = messages[levels]; $('#text').text(message); levels+=1; $('#level').text(levels+1); }; I didn’t understand why the for cycle works immediately and not step by step.

messages- ReinRaus