setInterval在for循环中立即激活

时间:2015-07-08 14:15:45

标签: javascript jquery

我尝试进行一系列调用以向Google API插入自定义事件, API中的限制是每秒10次查询,我尝试添加一个setInterval来限制这些调用,由于某种原因,它会立即触发所有内容, 这是我的测试功能:

function getGUIDS(){
$.ajax({
    url : 'google_api_url_with_params',
    type : 'get',
    success : function(data){
        for(var i in data.rows){
            rows[i] = data.rows[i];
            setInterval(function(x){
                console.log(data.rows[x][0]);
            },1000,i);
        }
    },
    error: function(data){
        console.log("Error",data);
    }
});

}

任何人?非常感谢!! :)

2 个答案:

答案 0 :(得分:1)

尝试设置作业队列:

var photoidx=0; // sample: pictures from a free JSONP provider ...
var stdJob={url : 'http://www.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=?',
      // format : 'json',  // not really necessary
      dataType:'jsonp',
      success : function(d){
                  $('#out').append('<img src="'+d.items[photoidx++].media.m+'">');},
      error: function(d){console.log("Error");}
    };         // object describing the standard AJAX job in JSONP mode
var jobs=[];   // job queue as a global variable

function getGUIDS(){ // IMPORTANT: $.extend() clones the stdJob
                     // before it is pushed into the job queue.
                     // Without cloning all jobs would have the same data.tags!
    jobs.push($.extend(true,{data:{tags: $('#topic').val()}},stdJob));
    // console.log(JSON.stringify(jobs[jobs.length-1])); 
}
setInterval(function(){if (jobs.length) $.ajax(jobs.pop());},100)

$(function(){
 $('#newjob').click(getGUIDS);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a href=# id=newjob>add pic</a> for topic
<input type="text" id="topic" value="Hannover"><br> <!-- my home town -->
<div id="out"></div>

setGUIDS()会将API请求放入作业队列。然后,每100毫秒调用setInterval()函数内的函数,然后相应地通过$.ajax()处理作业。这将确保API每秒不会被调用超过10次。

我稍微修改了你的例子以获得一个工作场景。

为了进行跨站点AJAX调用,您应该使用JSONP协议而不是POST,因为大多数浏览器都会阻止它。

答案 1 :(得分:0)

试试这个:

function getGUIDS(){
$.ajax({
url : 'google_api_url_with_params',
type : 'get',
success : function(data){
    for(var i in data.rows){
        rows[i] = data.rows[i];
        setTimeout(function(x){
            console.log(data.rows[x][0]);
        },i * 1000);
    }
},
error: function(data){
    console.log("Error",data);
}
});
}