Javascript / Jquery script terminated by timeout

雨燕双飞 提交于 2019-12-24 07:59:24

问题


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;  
         });
     }
    }
});

回答1:


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>



回答2:


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;');
        }
    });
});


来源:https://stackoverflow.com/questions/50275672/javascript-jquery-script-terminated-by-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!