【问题标题】:jQuery loop and append crashing the browserjQuery循环和追加崩溃浏览器
【发布时间】:2014-04-17 16:57:15
【问题描述】:

所以基本上,一旦单击特定图像,我就会尝试显示引导模式。然后,我尝试在段落标记中显示一些文本和图像,这些标记将每 600 毫秒更改一次,如下所示:

Playing -> Playing. -> Playing.. -> Playing...

一旦text 变为'Playing...',它将以'Playing' 的形式返回到开头,并一遍又一遍,直到Modal 的display 类变为none。

我在 setTimeOut 函数之后调用所有这些,因为我需要等待引导模式首先加载以针对其类进行测试。

虽然,我的代码每次都会导致浏览器崩溃,因此我无法查看开发者工具来找出问题所在。

$(".tutorial").click(function () {
    $('#tutorialModal').modal('show');
    $(this).toggleClass('playingGif'); //display 'playing' background image
    $(this).toggleClass('tutorial'); //turn off regular background image

    setTimeout(function () {
        while ($('#tutorialModal').css('display') == 'block') {
            var text = 'Playing';

            $('p', this)
            .delay(600)
            .queue(function (n) {
                $(this).html(text);
                n();
            });

            if (text == 'Playing...') {
                text = 'Playing';
            } else {
                text += '.';
            }
        }
    }, 500);
});

【问题讨论】:

  • @DamonSmith - 在 Chrome 和 Firefox 中崩溃。尚未在其他任何地方进行测试。
  • 它崩溃的原因可能是因为它处于一个繁忙的循环中,不断地排队运行函数,你可能认为因为存在延迟,while循环每步需要600毫秒但没有.
  • while ($('#tutorialModal').css('display') == 'block') 这是罪魁祸首。
  • @undefined - 我的方法有更好的选择吗?

标签: javascript jquery twitter-bootstrap


【解决方案1】:

试试这样的:

var text = 'Playing';
function startPlaying() {

  if($('#tutorialModal').css('display') == 'block') {


    $('p', this).html(text);
    n();

    if (text == 'Playing...') {
      text = 'Playing';
    } else {
      text += '.';
    }
    window.setTimeout(startPlaying, 500);
  }
}
startPlaying();

这样,它每 500 毫秒运行一次,它会更新正在播放的...文本,然后如果它仍然显示,它将在另一个 500 毫秒内排队再次运行该函数。我没有尝试这段代码,只是为了给你一个大致的想法。

【讨论】:

  • 将 startPlaying() 更改为 window.setTimeout(startPlaying, 500); 并删除了 n();,它就像一个魅力。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多