【问题标题】:Using setTimeout with jQuery each将 setTimeout 与 jQuery 一起使用
【发布时间】:2017-04-29 02:11:10
【问题描述】:

我想在第一个 $.each 的每次迭代之间添加 500 毫秒的暂停

我不确定如何应用此解决方案: How to add pause between each iteration of jQuery .each()?

针对我的特殊情况:

function iterateAddresses () {

  var time = 500;

  $.each( addresses_google, function( index, value ) {
    var service = new google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
      {
        origins: [origin],
        destinations: value,
        travelMode: 'DRIVING'
      },
      callback
    );

    function callback(response, status) {
      var origins = response.originAddresses;
      var destinations = response.destinationAddresses;
      for (var i = 0; i < origins.length; i++) {
        var results = response.rows[i].elements;
        for (var j = 0; j < results.length; j++) {
          var element = results[j];
          if(element.status == "NOT_FOUND"){
            var distance = 0;
          } else {
            var distance = element.distance.value;
          }
          if(distance > radius){
            // Store postids in array
            postids_to_hide.push(
              addresses_postids[index][j]
            );
            // Hide elements where postid is in the postids_to_hide arrays
            $.each( postids_to_hide, function( index, value ) {
              $(".main_short_post_div").filter(function(){
                return $(this).attr('data-post-id') === value;
              }).hide();
            });
          } // end if d < r
        } // end for j
      } // end for i
    } // end callback function
  }); // end each addresses_google

}; // end iterateAddresses

iterateAddresses();

【问题讨论】:

  • 如您所见,我的迭代中有一大堆代码、函数参数和变量。这就是我的难处。
  • 所以将东西添加到集合中,使用超时并从集合中删除项目。
  • 变量 fromto 未使用?

标签: javascript jquery each settimeout


【解决方案1】:

你可以在你的 iterateAddresses() 函数之后调用的其他函数中分开

function iterateAddresses () {

  var time = 500;
  // Then get a random number between 500 and 599    
  $.each( addresses_google, function( index, value ) {
        var ram = Math.floor(Math.random() * (599-time+1)) + time;
        setTimeout( "OtherFunction("+index+","+value+");", ram);
  }); // end each google_address

}; // end iterateAddresses


function OtherFunction(index, value)
{
    var service = new google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
      {
        origins: [origin],
        destinations: value,//addresses_google,
        travelMode: 'DRIVING'
      },
      callback
    );

    function callback(response, status) {
      var origins = response.originAddresses;
      var destinations = response.destinationAddresses;
      for (var i = 0; i < origins.length; i++) {
        var results = response.rows[i].elements;
        for (var j = 0; j < results.length; j++) {
          var element = results[j];
          if(element.status == "NOT_FOUND"){
            var distance = 0;
          } else {
            var distance = element.distance.value;
          }
          var from = origins[i];
          var to = destinations[j];
          if(distance > radius){
            // Store postids in array
            postids_to_hide.push(
              addresses_postids[index][j]
            );
            // Hide elements where postid is in the postids_to_hide arrays
            $.each( postids_to_hide, function( index, value ) {
              $(".main_short_post_div").filter(function(){
                return $(this).attr('data-post-id') === value;
              }).hide();
            });
          } // end if d < r
        } // end for j
      } // end for i
    } // end callback function
}

iterateAddresses();

【讨论】:

  • 我认为这里唯一的问题是每次迭代都同时执行,每次迭代都需要增加 var 时间。如果我用“时间”替换代码中的“500”并添加一个增量,我会得到一大堆错误。
  • 我提出了一个改进的随机数,介于 500 和 599 之间。
【解决方案2】:
function asyncForEach(arr, cb) {
    return arr.reduce((p,c)=>{
        return p.then(()=>cb(c));
    }, Promise.resolve());
}
function wait(ms) {
    return ()=>new Promise(resolve=>setTimeout(resolve, ms));
}

const DELAY = 500; //ms
function iterateAddresses() {
    return asyncForEach(addresses_google, address => 
      getDistanceMatrix(address)
        .then(processResult)
        .then(wait(DELAY)));
}

iterateAddresses();

getDistanceMatrix 是您提供给$.each 的函数的承诺版本。

processResultcallback 的承诺版本。

【讨论】:

  • 我如何承诺这些? :-) 直到今天才听说过 JS 承诺,我正在阅读它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-22
  • 1970-01-01
  • 2019-11-30
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
相关资源
最近更新 更多