簡體   English   中英

如何每 3.5 秒調用一次 javascript 函數?

[英]How to invoke javascript function every 3.5 seconds?

在 drop 函數中,我在從數組迭代每個值后調用 show div。showdiv 函數將 div 設置為display:block; 並顯示其中的數據。在顯示 div 函數中,我試圖在顯示 div 后每 3.5 秒隱藏一次 div,當再次完成下一次迭代時,它不再顯示 div,僅第一次顯示 div有時,它會隱藏 div。 當它再次調用 showdiv 函數時,它沒有顯示 div。

我想顯示 div,3.5 秒后我想隱藏 div。我該怎么做?

function drop() {
  clearMarkers();
  for (var i = 0; i < locations.length; i++) {
    var city = locations[i][0];
    var pro_cat = locations[i][1];
    var marker_icon = locations[i][3];
    var product_image = locations[i][4];
    var marker_src = 
    addMarkerWithTimeout(locations[i][2], i * 500, marker_icon);  
    //alert("dropped");
    getCity(city,pro_cat, i * 500);
    if(product_image == null)
    {
        //if image found in row-do nothing
    }
    else {
      //if image found 
      showdiv(city,product_image, i * 500);
      /*window.setTimeout(function() {
         hidediv();
      },2500);*/
    }
  }
}



function showdiv(city, imagesrc, timeout)
{
  window.setTimeout(function() {
  document.getElementById('city-order').innerHTML = "";
  document.getElementById('order-product').innerHTML = "";
  $('.product-display').addClass("zoomin");  
  //document.getElementById('product-view-display').style.display = "block";  
  document.getElementById('product-list-display').style.display = "block";
  var order_placed_city = document.getElementById('city-order');
  var content = document.createTextNode(city);
  order_placed_city.appendChild(content);
  var product_order = document.getElementById('order-product');
  var elem = document.createElement("img");
  product_order.appendChild(elem);
  elem.src = imagesrc;
  },timeout);  
   window.setTimeout(function() { 
      document.getElementById('product-view-display').style.display = "none";  
   },3500);
}
setInterval(function(){
    $('.product-view-display').toggle(); },
3500);

請改用setInterval 超時調用該函數一次。 Interval 將在指定的時間段(毫秒)后繼續調用該函數。

如果您最終需要停止此操作,請參閱: 在 JavaScript 中停止 setInterval 調用

更多關於 jQuery 切換: http : //api.jquery.com/toggle/

您的代碼的問題在於您安排了顯示,同時安排了隱藏。 這意味着根據給定的超時,隱藏將立即撤消顯示。

您應該在setTimeout的回調中安排下一步。

所以你更願意做的是:

function scheduleShowDiv(city, imageSrc, timeout) {
  window.setTimeout(function() { showDiv(city, imageSrc, timeout) }, timeout)
}

function showDiv(city, imageSrc,timeout) {
  /* do whatever you need to show the div */
  window.setTimeout(function() {
    document.getElementById('product-view-display').style.display = "none";
    scheduleShowDiv(city, imageSrc, timeout);
  }, timeout);
}

另一種方法是使用setInterval並檢查 div 的存在來決定是要顯示和更新內容,還是只是隱藏它。

只需使用下面設置 3.5 秒間隔的 javascript 方法

 setInterval(function () { // write here code that you want to execute..... }, 3500);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM