如何每3.5秒调用一次javascript函数

How to invoke javascript function every 3.5 seconds?

本文关键字:一次 javascript 函数 何每 5秒 调用      更新时间:2023-09-26

在drop函数中,我在从数组中迭代每个值后调用showdiv。showdiv函数将div设置为display:block;,并显示其中的数据。在showdiv函数中,在显示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。Timeout调用函数一次。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的存在,以决定是要显示和更新内容,还是只是隐藏它

只需使用下面的javascript方法即可设置3.5秒的间隔

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