Home > Blockchain >  local webpage is still loading for using while loop
local webpage is still loading for using while loop

Time:01-30

When I am using for loop it's working perfectly but when I try to run this code with while loop and it's stuck loading.

// for (var i = 0; i < 7; i  ) {
//    document.querySelectorAll("button")[i].addEventListener("click", 
//        function () {
//            alert("Hi there! I'm working ");
//        }
//    );
// }

var i = 0;
while (i < 7) {
    document.querySelectorAll("button")[i].addEventListener("click", 
        function () {
            alert("Hi there! I'm working ");
            i  ;
        }
    );
}

CodePudding user response:

This is the equivalent loop with while

var i = 0;
while (i < 7) {
    i  ;
    document.querySelectorAll("button")[i].addEventListener("click", function () {
        alert("Hi there! I'm working ");
  });
}

What your previous code did, is that it kept on adding an event listener that would try to update the i variable on click but since your page never loaded, it did not have the chance (nor would the code be correct if it did).

CodePudding user response:

A working solution can be as easy as this:

// for (var i = 0; i < 7; i  ) {
//    document.querySelectorAll("button")[i].addEventListener("click", 
//        function () {
//            alert("Hi there! I'm working ");
//        }
//    );
// }

var i = 0;
while (i < 7)
    document.querySelectorAll("button")[i  ].addEventListener("click", 
        function () {
            alert("Hi there! I'm working ");
        }
    );
<button>a</button><br>
<button>b</button><br>
<button>c</button><br>
<button>d</button><br>
<button>e</button><br>
<button>f</button><br>
<button>g</button><br>
<button>h</button>

  • Related