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

时间:2015-06-29 13:00:04

标签: javascript jquery

这里是drop函数我在从数组迭代每个值后调用show div。showdiv函数将div设置为display:block;并显示其中的数据。显示div函数我试图隐藏div显示后每隔3.5秒再次完成下一次迭代后再次显示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);
}

3 个答案:

答案 0 :(得分:3)

setInterval(function(){
    $('.product-view-display').toggle(); },
3500);

请改用setInterval。超时调用该函数一次。 Interval将在指定的时间段(毫秒)后继续调用该函数。

如果您最终需要停止此操作,请参阅:Stop setInterval call in JavaScript

有关jQuery切换的更多信息:http://api.jquery.com/toggle/

答案 1 :(得分:1)

您的代码的问题在于您安排了显示,同时安排隐藏。这意味着根据给定的超时时间,隐藏会立即撤消显示。

您应安排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的存在,以决定是否要显示和更新内容,或者只是隐藏它。

答案 2 :(得分:0)

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

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