Poffert
Poffert

Reputation: 51

Javascript / Jquery script terminated by timeout

So as a python guy I am experimenting with JS and Jquery. I wrote this small script to fold \ unfold a menu bar on a html page using Jquery slide. I believe this should work fine, however all it does is freezing my browser for around 10 secs after which in the console I get "script terminated by timeout". Anyone can point me in the right direction?

$(document).ready(function(){   
    var Clicked = false; 
    while (true) {
    if (Clicked) {
        $("button").click(function(){
            $("#menu").slideDown();
            $("button").replaceWith("<button type=\"button\">&#8593;</button>");
            Clicked = false;  
        });
     } else {
         $("button").click(function(){
             $("#menu").slideUp();
             $("button").replaceWith("<button type=\"button\">&#8595;</button>");
             Clicked = true;  
         });
     }
    }
});

Upvotes: 5

Views: 8308

Answers (2)

Vaidas
Vaidas

Reputation: 1503

Your while loop is infinite. It keeps going to an else section and attaching onClick events to the button. I think you can simplify your code by eliminating unnecessary loop, Clicked variable and using only one onClick event handler to toggle menu.

I also changed replaceWith method with jQuery's html() which just takes HTML code as a parameter and puts it inside of your button depending on it's visibility.

$(document).ready(function(){   
    $("button").click(function(){
        $("#menu").slideToggle();
        var thisButton = $(this);
        if (thisButton.is(':visible')) {
            thisButton.html('&#8593;');
        } else {
            thisButton.html('&#8595;');
        }
    });
});

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is due to the while() loop. In JS this is a synchronous operation which blocks all other threads (including, importantly, the UI renderer) which causes the browser to hang. This is why you see the alert stating that the operation has been terminated.

A better approach to this is to just have a single event handler which toggles the state of #menu and the text in the button which is clicked. Try this:

$(function() {
  $("button").click(function() {
    $("#menu").slideToggle();
    $(this).html(function(i, h) {
      return h === '↑' ? '↓' : '↑';
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button">&#8595;</button>
<div id="menu">
  Menu...
</div>

Upvotes: 5

Related Questions