setTimeout会触发多少次

时间:2016-04-21 00:25:02

标签: 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如何工作,它只会触发一次还是会执行多次?当然,我仅为测试目的添加了警报...

由于

1 个答案:

答案 0 :(得分:1)

        // 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()在提供的延迟后调用提供的函数,只调用一次。