我正在尝试设置从 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 + "')");
});
});
最佳答案
我会使用 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);
});
关于javascript - 设置 json 调用的间隔以重新加载新图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32950870/