2016-04-21 79 views
0

我有我的asp.net mvc的網站裏面的下面的代碼: -應該有多少次的setTimeout火災

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的作品只會觸發一次或執行多次?當然我添加僅用於測試目的的警報......

感謝

+6

setTimeout只是在您定義N毫秒後執行一次函數。可能您的應用程序正在多次調用您的loadImage函數... –

+2

不要使用警報進行調試。使用控制檯 – epascarello

+0

如果您想在n秒後一直重複調用您的函數,請使用'setInterval' – Rash

回答

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()在提供的延遲後調用提供的功能,只需一次。