我试图设置将从Flickr API重新加载新图像的间隔。
我需要添加什么才能让网页使用setInterval
抓取新图片。
这是我的代码:
$(document).ready(function(){
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tagmode: "any",
format: "json"
},
function(data) {
var rnd = Math.floor(Math.random() * data.items.length);
var image_src = data.items[rnd]['media']['m'].replace("_m", "_b");
$('.main').css('background-image', "url('" + image_src + "')");
});
});
答案 0 :(得分:1)
我使用setTimeout
代替setInterval
,以防由于网络延迟而需要超过[interval]秒才能获取图片。
$(document).ready(function() {
var INTERVAL_IN_MS = 1000; // wait 1 second
function getImage() {
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tagmode: "any",
format: "json"
}, function(data) {
var rnd = Math.floor(Math.random() * data.items.length);
var image_src = data.items[rnd]['media']['m'].replace("_m", "_b");
$('.main').css('background-image', "url('" + image_src + "')");
// start the timeout countdown only after the previous image has been fetched and displayed
window.setTimeout(getImage, INTERVAL_IN_MS);
});
}
window.setTimeout(getImage, INTERVAL_IN_MS);
});