0

I would like to load multiple image with JavaScript and wrote the code below. I expected it should output "0 1 2" but unfortunately it output just "3" once. I don't know Why. Anyone, please help me!!

<!DOCTYPE html>
<html>
<head></head>
    <body>
        <script type="text/javascript">
            for (var i = 0; i < 3; i++) {
                var imageObj = new Image();
                imageObj.addEventListener('load', function() {
                    console.log(i);
                });
                imageObj.src = './assets/REACT.png';
            }
        </script>
    </body>
</html>
Rio
  • 59
  • 6
  • Someone responded stating that this question already has answers at https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example and closed my question. But I think the page of the link doesn't solve my question because it doesn't load image files. While my code is trying to load image files. Should I ask my question again as a new question? This is the first time to ask here. – Rio May 01 '20 at 22:50
  • 1
    Hello Rio although it's not directly answering your question but it shows you the real problem you are facing and how to solve it, and you can now do that with you image load function – Saadi Toumi Fouad May 01 '20 at 22:55
  • 1
    you can use the let keyword `for(let i = 0;i < 3; i++) { var imageObj = new Image(); imageObj.addEventListener('load', function() { console.log(i); }); imageObj.src = './assets/REACT.png'; };` – Saadi Toumi Fouad May 01 '20 at 22:59
  • Dear Mr./Ms. SaymoinSam, Yes!! You solved it!! You are so nice. What a great and kind person you are! I was so lucky to have your comment. I'll remember you! Thank you so much!! – Rio May 01 '20 at 23:50
  • 1
    You are welcome, I'm here to help, and glad I did :) – Saadi Toumi Fouad May 01 '20 at 23:53
  • What a kind word! Thank you so much. It was warm experience. I will use your handle name "saymoinsam" somewhere as a password:-). You are my luck!! – Rio May 02 '20 at 04:27
  • You make me feel like I built a rocket for you :D, stay safe and happy coding ;) – Saadi Toumi Fouad May 02 '20 at 15:19

0 Answers0