dcsimg
www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16

Thread: Loop condition not checked

  1. #1
    Join Date
    Jan 2017
    Posts
    6

    Loop condition not checked

    Hey, this is my first post here. I recently started learning about web development. At the moment I am struggling with javascript. I tried writing an reaction time tester, that lets the user click on boxes which appear at random position (in the test just 2 positions). After a lot of learning about the event driven paradigm I have an almost working code.
    However, I'm using a while loop to restrict the number of user clicks, but somehow the condition in the while loop isn't rechecked, what makes it an endless loop. Maybe someone of you is familiar with such an issue. Thanks already.

    (Note: I posted this question already at Stack Overflow (using a for loop instead of forEach), there people don't seem to have enough time to really check the code. it was marked as a duplicate of closures in loops, which was not the case since I used
    Code:
    let
    to define a local variable in the
    Code:
    for
    loop.)

    Here is the code (as simple as possible, but working):

    Code:
    <!doctype html>
    <html>
    <head>
       <meta charset="utf-8" />
       <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
       <meta name="viewport" content="width=device-width, initial-scale=1" />
       <style type="text/css">
       .buttonBox{
          background-color:red;
          padding:50px;
          border: none;
       }
       #ersteBox{
          position:absolute;
          left:500px;
          top:300px;
          display:none;
       }   
       #zweiteBox{
          position:absolute;
          left:500px; 
          top:600px;
          display:none;
       }      
       </style>
    </head>   
              
    <body> 
       <div>Click the appearing boxes as fast as possible!</div>
       <button id="starter">Startknopf</button>
              
       <button id="ersteBox" class="buttonBox"> </button>
       <button id="zweiteBox" class="buttonBox"> </button>
           
       <script>
           var boxesi=["ersteBox","zweiteBox"];
           var j=0;
           var buttons=[].slice.call(document.getElementsByClassName("buttonBox"));
           
           document.getElementById("starter").onclick=function(a){
              show_random();
              while ( j<4 ){
                 buttons.forEach(function(box,k){
                    box.onclick=function(){
                       console.log(k);
                           if (k==i) {
                          box.style.display="none";
                              show_random();
                              j=j+1;
                          console.log(j);
                       };
                    };
                 });
                 a();
              };
              alert("done");
               };
    
           function show_random(){
              i=Math.floor(Math.random()*2);
              var b=boxesi[i];
              document.getElementById(b).style.display="inline";
           };
       </script>
    </body>
    </html>

  2. #2
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    4,025
    <!doctype html> needs to be <!DOCTYPE html> upper case capitals.

    I see a variable k but don't see any variable set up for it.

    How many times is the function meant to trigger... if its completely controlled by the array created for the buttons and its going to execute the loop at least once, you could use a do..while, forget using the .forEach and just grab the reference and apply an onclick attribute to the current

    Code:
    do{
    // do stuff...
    var currentButton = buttons.shift(); // get a button off the array
    currentButton.setAttribute("onclick",  function(){ /* something to do*/ });
    ...
    ...
    }while(buttons.length);
    when the array is depleated to a 0 length. the loop stops but will always do one iteration of the loop
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  3. #3
    Join Date
    Jan 2017
    Posts
    6
    Quote Originally Posted by \\.\ View Post
    <!doctype html> needs to be <!DOCTYPE html> upper case capitals.
    Thanks, but what is the difference?

    I see a variable k but don't see any variable set up for it.
    Isn't it defined implicitly in the foreach?

    How many times is the function meant to trigger... if its completely controlled by the array created for the buttons and its going to execute the loop at least once, you could use a do..while, forget using the .forEach and just grab the reference and apply an onclick attribute to the current

    Code:
    do{
    // do stuff...
    var currentButton = buttons.shift(); // get a button off the array
    currentButton.setAttribute("onclick",  function(){ /* something to do*/ });
    ...
    ...
    }while(buttons.length);
    when the array is depleated to a 0 length. the loop stops but will always do one iteration of the loop
    [/QUOTE]

    Thank you. The problem is (as far as I see) not the forEach. I will definitely try your code.
    However, the problem is the while loop. It is supposed to run as often as I say and does not depend on the length of the array. The buttons are supposed to jump as often as I want them to. Actually I would need only one button for each cycle of the while loop - the one which has to be clicked. This was just the first working version for me.
    Just, the j is counted but the loop happily runs over its upper bound.

  4. #4
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    4,025
    <!DOCTYPE html> sets HTML5, lowercase is not a recognised tag and the browser defaults to quirks mode which can have unexpected results.

    Having tried the script, error message of a is not a function is given, clicking the start button does nothing.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  5. #5
    Join Date
    Jan 2017
    Posts
    6
    Quote Originally Posted by \\.\ View Post

    Having tried the script, error message of a is not a function is given, clicking the start button does nothing.
    I do see the error message too. It seems that this always happens when a callback function is used as I did use a here.
    Which Browser are you using? I just tried Chrome, Safari, and Firefox. Which click at Start, a red box should appear. Clicking on this box should let it disappear and another box appear at the same or at another place. At click on this, the same should happen again, usually until the while loop is finished.

  6. #6
    Join Date
    Oct 2013
    Posts
    1,585
    Quote Originally Posted by \\.\ View Post
    <!doctype html> needs to be <!DOCTYPE html> upper case capitals.
    Quote Originally Posted by PeMa View Post
    Thanks, but what is the difference?
    Quote Originally Posted by \\.\ View Post
    <!DOCTYPE html> sets HTML5, lowercase is not a recognised tag and the browser defaults to quirks mode which can have unexpected results.
    The truth of the matter is that there is no difference. Here's the spec on the HTML5 doctype. Notice that it specifically states that it is case-insensitive.
    https://www.w3.org/TR/html5/syntax.html#the-doctype

    Using any case-insensitive version of that doctype will trigger "standards" mode in any reasonably modern browser. I did look it up and MS says that IE6 (and maybe IE7?) will not go into standards mode when the doctype does not have the URL included in it, like the HTML4 and XHTML doctypes had.
    Source: https://msdn.microsoft.com/en-us/lib...(v=vs.85).aspx
    So capitalized or not <!DOCTYPE html> will trigger quirks mode in that/those browsers. On the other hand the IE6/IE7 "emulators" in IE11's developer tools have standards mode triggered with any capitalization. Go figure.

    Still don't believe these authoritative sources? Try this:
    HTML Code:
    <!DOCTYPE html>
    <title>standards vs. quirks mode test</title>
    
    <h1>standards vs. quirks mode test</h1>
    
    <p>Change the case of the DOCTYPE statement to anything you want -- all caps, all lower case, CaMeL cAsE, some other mix. Save, open/refresh, click on the link below. If the alert states <b>CSS1Compat</b> that's "standards mode". If the alert states <b>BackCompat</b> that's "quirks mode".</p>
    
    <a href="javascript:alert(document.compatMode);">What mode am I?</a>
    There is apparently one exception. If your HTML file will be processed or "serialized" somehow using XML, DOCTYPE must be capitalized. If not the parser will choke and throw an error. But if you are doing that you have more to worry about than capitalization. The document must also conform to XML syntax. In other words, no unclosed tags, e.g. <br> must be <br/>, no attribute "shorthand", e.g.<input type="text" required> must be <input type="text" required="required"> and more. I have a custom web app on a website that this actually factors in. It's a XML "database" that gets processed through a few XSL templates via PHP on the server. One missing self-closing slash crashes the whole thing.

    Don't worry about it. If you want to live dangerously make it CaMeL cAsE. It'll still trigger standards mode.
    In dog beers I've only had one.

  7. #7
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    4,025
    Pretty much everywhere puts <!DOCTYPE and several articles I read states pretty much the same that <!doctype is a meaningless element and using it will result in a likley case of quirks mode. I figure thats because <!DOCTYPE in all capitals is what the browsers parser engines looking for and anything else is fair game.

    As for the HTML code, its missing <title> tags in the <head> has a couple of declarations in the <meta> tags that are questionable.

    The script itself IMHO should not be using getElementsByClassName without offering the work around for older browsers that may not be supporting that method or simply switch it for a getElementsByName and use name attributes and use a conventional looping method rather than the forEach method, many articles don't rate its reliability in terms of speed and some reckon the overhead makes it 95% slower than long established methods, why I don't know, maybe its been tested, who knows.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  8. #8
    Join Date
    Dec 2012
    Posts
    1,061
    Hallo Kevin2, thanks for having clarified the facts regarding upper/lowercase doctype. I tried before but //.// didn't believe just as he doesn't now. It's annoying that he continues spreading faulty information in this forum.

  9. #9
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    4,025
    Quote Originally Posted by Sempervivum View Post
    Hallo Kevin2, thanks for having clarified the facts regarding upper/lowercase doctype. I tried before but //.// didn't believe just as he doesn't now. It's annoying that he continues spreading faulty information in this forum.
    I don't spread faulty anything. Even the W3C site I am looking at show <!DOCTYPE html> as being the correct way to start an HTML file.

    HTML Code:
    A basic HTML document looks like this:
    
    <!DOCTYPE html>
    <html>
      <head>
        <title>Sample page</title>
      </head>
      <body>
        <h1>Sample page</h1>
        <p>This is a <a href="demo.html">simple</a> sample.</p>
        <!-- this is a comment -->
      </body>
    </html>
    Notice the first line?

    and a random link from 822,000 results on the subject of <!doctype vs <!DOCTYPE https://www.codecademy.com/en/forum_...292fc5e10000c9
    Why will my <!doctype html> tag not register
    Carry on as you are, see if I care, what I state is not misinformation so stick that up your jacksies and smoke it.
    Last edited by \\.\; 01-05-2017 at 09:16 PM.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  10. #10
    Join Date
    Oct 2013
    Posts
    1,585
    "Never let a fact get in the way of a good opinion." -- unknown

    Capitalizing DOCTYPE is convention and tradition -- a leftover from HTML4 and XHTML1.x. And the link to the post at codecademy just repeats the exception I pointed out above about processing as XML. Apparently whatever they are discussing (SCT -- submission correctness test??? WTF is that?) has some XML processing going on. As I previously stated, if that's the case you MUST use the capitalized version.

    But the exception does not prove the rule! While it is absolutely correct to use DOCTYPE in, well, "normal" HTML it is just as correct to use doctype or dOcTyPe or DOCtype or docTYPE. That's in the W3C HTML5 spec. It's not my opinion, it's the specification. The example you repeat from W3C is just that -- an example, not a rule. If you don't like or agree with the spec or how it is implemented within browsers you need to schedule an audience with Tim Berners-Lee and discuss it with him.

    One more quote:
    "Those who don't read [...] have no advantage over those who can't." -- attributed to Mark Twain
    I'll edit the first phrase to say: "Those who don't read with an open mind..."
    In dog beers I've only had one.

  11. #11
    Join Date
    Aug 2016
    Posts
    91
    are you certain !doctype is case insensitive in ie6 ?
    what about the other lesser known browsers ?
    it would be nice if all browsers adhered to the specs
    none do

    from https://msdn.microsoft.com/en-us/lib...(v=vs.85).aspx ...

    "Conclusion
    In general, most public websites should declare the HTML5 document type
    so that they are displayed in standards mode,
    which reflects the strongest support available to a browser for industry standards.
    To do so, start each of your webpages with the following line.
    <!DOCTYPE html> "

    have you a good argument for
    NOT respecting convention
    and tradition ?

  12. #12
    Join Date
    Jan 2017
    Posts
    6
    ähm, don't want to disturb. But you all seem quite familiar with web development, so does maybe anyone know the answer to my actual question?

  13. #13
    Join Date
    Aug 2016
    Posts
    91
    Code:
    <!doctype html>
    <html>
    <head>
       <meta charset="utf-8" />
       <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
       <meta name="viewport" content="width=device-width, initial-scale=1" />
       <style type="text/css">
       .buttonBox{
          background-color:red;
          padding:50px;
          border: none;
       }
       #ersteBox{
          position:absolute;
          left:500px;
          top:300px;
          display:none;
       }   
       #zweiteBox{
          position:absolute;
          left:500px; 
          top:600px;
          display:none;
       }      
       </style>
    </head>   
              
    <body> 
       <div>Click the appearing boxes as fast as possible!</div>
       <button id="starter">Startknopf</button>
              
       <button id="ersteBox" class="buttonBox"> </button>
       <button id="zweiteBox" class="buttonBox"> </button>
           
       <script>
           var boxesi=["ersteBox","zweiteBox"];
           var buttons=[].slice.call(document.getElementsByClassName("buttonBox"));
    buttons.forEach(function(box){
                    box.onclick=function(){
                       show_toggle()
                       };                
                 });
           var j=false;
           document.getElementById("starter").onclick=function(a){
              show_toggle();               
              };       
              
    var only4times=4;
           function show_toggle(){
    	if(j)j=1
    	else j=0;
    	var b=boxesi[j];
              document.getElementById(b).style.display="none";
    if(only4times--){
    
              j=!j;
    	  if(j)j=1
    	else j=0;
              var b=boxesi[j];
              document.getElementById(b).style.display="inline";}
           };
       </script>
    </body>
    </html>

  14. #14
    Join Date
    Aug 2016
    Posts
    91
    Quote Originally Posted by PeMa View Post
    ähm, don't want to disturb. But you all seem quite familiar with web development, so does maybe anyone know the answer to my actual question?
    I will try to explain the problem with your while loop ...

    the dom controls what you see in the browser

    javascript can make changes to the dom

    while javascript is running the dom does not change

    the things that happen one by one in the loop
    are not reflected in the dom, only the final state
    is actually seen in the browser

  15. #15
    Join Date
    Jan 2017
    Posts
    6
    Quote Originally Posted by shakazorba View Post
    Code:
    <!doctype html>
    <html>
    <head>
       <meta charset="utf-8" />
       <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
       <meta name="viewport" content="width=device-width, initial-scale=1" />
       <style type="text/css">
       .buttonBox{
          background-color:red;
          padding:50px;
          border: none;
       }
       #ersteBox{
          position:absolute;
          left:500px;
          top:300px;
          display:none;
       }   
       #zweiteBox{
          position:absolute;
          left:500px; 
          top:600px;
          display:none;
       }      
       </style>
    </head>   
              
    <body> 
       <div>Click the appearing boxes as fast as possible!</div>
       <button id="starter">Startknopf</button>
              
       <button id="ersteBox" class="buttonBox"> </button>
       <button id="zweiteBox" class="buttonBox"> </button>
           
       <script>
           var boxesi=["ersteBox","zweiteBox"];
           var buttons=[].slice.call(document.getElementsByClassName("buttonBox"));
    buttons.forEach(function(box){
                    box.onclick=function(){
                       show_toggle()
                       };                
                 });
           var j=false;
           document.getElementById("starter").onclick=function(a){
              show_toggle();               
              };       
              
    var only4times=4;
           function show_toggle(){
    	if(j)j=1
    	else j=0;
    	var b=boxesi[j];
              document.getElementById(b).style.display="none";
    if(only4times--){
    
              j=!j;
    	  if(j)j=1
    	else j=0;
              var b=boxesi[j];
              document.getElementById(b).style.display="inline";}
           };
       </script>
    </body>
    </html>
    Great, that's it! I tried if before, just outside of the forEach ... stupid me.
    And sorry for the late answer, I was not around for some days.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles