jQuery:函数在使用setTimeout时不会执行两次

jQuery: function not excecuted twice when using setTimeout

本文关键字:执行 两次 函数 setTimeout jQuery      更新时间:2023-09-26

我有以下代码和函数"placeNewSponsor"应该每4秒重复一次。(该函数应该放置图像,在3秒后隐藏它们,等待1秒并重复自己)。但是当我测试这个时,这个函数只执行一次。

function placeNewSponsor() {
  $('.sponsorContainer').each(function() {
    var imageCount = $(".imageContainer").children().length;
    do {
      randomInt = Math.floor(Math.random() * imageCount + 1);
    } while ($.inArray(randomInt, usedNumbers) !== -1);
    usedNumbers.push(randomInt);
    var randomImage = $('.imageContainer a:nth-child(' + randomInt + ')').clone();
    $(this).append(randomImage);
  });
  usedNumbers = [];
  // Hide after 3 seconds
  setTimeout(function() {
    $('.sponsorContainer').hide();
  }, 3000);
  // Re-activate function
  setTimeout(placeNewSponsor, 4000);
}
placeNewSponsor();

您隐藏了容器,但永远不会重新显示它们。

$('.sponsorContainer').show();  //show them
setTimeout(function(){ $('.sponsorContainer').hide(); }, 3000);  //hides them