Javascript / Jquery脚本因超时而终止 [英] Javascript / Jquery script terminated by timeout
问题描述
所以作为一个python人我正在试验JS和Jquery。我写了这个小脚本来折叠\使用Jquery幻灯片展开html页面上的菜单栏。我相信这应该可以正常工作,但它所做的就是冻结我的浏览器大约10秒钟,之后在控制台中我得到脚本因超时而终止。任何人都可以指出我正确的方向吗?
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\">↑</button>");
Clicked = false;
});
} else {
$("button").click(function(){
$("#menu").slideUp();
$("button").replaceWith("<button type=\"button\">↓</button>");
Clicked = true;
});
}
}
});
推荐答案
问题是由于 while()
循环。在JS中,这是一个同步操作,它阻止导致浏览器挂起的所有其他线程(包括重要的UI渲染器)。这就是为什么你看到警告声明操作已经终止的原因。
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.
更好的方法是只有一个事件处理程序切换<$的状态单击c $ c> #menu 和按钮
中的文本。试试这个:
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">↓</button>
<div id="menu">
Menu...
</div>
这篇关于Javascript / Jquery脚本因超时而终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!