javascript - setTimeout 应该触发多少次

标签 javascript jquery settimeout

我的 asp.net mvc 网站中有以下代码:-

function loadImage(src, callback) {
  var img = $('<img>').on('load', function () {
    callback.call(img);
  });

  img.attr('src', src);
  var allcaptions = $("figure span");

  // setTimeout is a hack here, since the ".placeholders" don't exist yet
  setTimeout(function () {
    alert(1);
    $(".placeholder").each(function (i) {

      // in each .placeholder, copy its caption's mark-up into it (remove the img first)
      var caption = allcaptions.eq(i).clone();
      //caption.find("img").remove();
      var t = caption.find("img").attr('data-goto');

      // caption.append($("<a />", { "text": "test", "href": t }));
      if (!(t == null || t == "undefined")) {
        caption.append("<br/>");
        caption.append("<a href='" + t + "' style='font-size:16px;font-weight:bold'>Read More</a>");
      }

      caption.find("img").remove();
      $(this).append("<div class='caption'>" + caption.html() + "</div>");
    });
  }, 500);
  alert(2)
}

现在根据我的理解,settimout 将在 500 毫秒后触发并调用该函数。但实际发生的情况如下:-

当调用该函数时(显示图片库时),我将收到以下警报:-

2
1
2
2
1 
1

请问有人可以对此提出建议吗,setTimeout 是如何工作的,它是只触发一次还是会执行多次?当然,我添加警报仅用于测试目的......

谢谢

最佳答案

        // setTimeout is a hack here, since the ".placeholders" don't exist yet

MutationObserverwide support这些日子。

var $container = $('.container'),
  observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      var placeholders = Array.prototype.filter.call(mutation.addedNodes, function(node) {
        return node.className === 'placeholder';
      });

      if (placeholders.length > 0) console.log(placeholders);
    });
  });

observer.observe(document, {
  childList: true,
  subtree: true
});

var placeholders = setInterval(function() {
    $container.append('<p class="placeholder">Hello world</p>');
  }, 500),
  goodbyes = setInterval(function() {
    $container.append('<p class="goodbye">Goodbye world</p>')
  }, 1000);

setTimeout(function() {
  clearInterval(placeholders);
  clearInterval(goodbyes);
}, 3500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
</div>

<小时/>
  • loadImage() 必须被多次调用。
  • setTimeout()在提供的延迟后调用提供的函数,仅一次。

关于javascript - setTimeout 应该触发多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36757516/

相关文章:

javascript - 父子关系对应的REST调用如何判断和调用

javascript - 从 Playbook 应用程序打开文件

javascript - 使用 scrollTop 的错误箭头键导航

javascript - 取消为一个 ID 设置的多个超时

javascript - 'setTimeOut' 在 JavaScript 'for' 循环中调用,为什么会失败?

javascript - 无法安装 craco

javascript - Javascript 好的编程风格的简单示例?

jquery - 可转换的 可转换的

javascript - 带有对话泡泡的聊天窗口 - html

JavaScript 不能在循环中使用多个 setTimeout 函数