我得到一个随机单词,然后使用该单词生成GIF。我的代码仅运行一次。我希望它生成另一个单词并获得另一个图像而无需刷新浏览器。
所以,我通过使用setInerval();
传递获取图像的函数来使用[C0
fetch()
据我所知const section = document.getElementById('main');
const text = document.querySelector('.word');
let wordurl = 'https://random-word-api.herokuapp.com/word?number=1&swear=0';
let giphyapikey = '62urPH2PxR2otT2FjFFGNlvpXmnvRVfF';
//Setinterval
setInterval(wordgif(), 5000);
//make WordGIF call
function wordgif() {
wordGIF().then(results => {
text.innerHTML = results.word;
section.innerHTML = `<img src=${results.imgurl}>`;
}).catch(err => console.error(err))
}
//Async/await
async function wordGIF() {
let fetchword = await fetch(wordurl);
let word = await fetchword.json();
console.log(word)
let fetchgif = await fetch(`http://api.giphy.com/v1/gifs/search?q=${word}&api_key=${giphyapikey}&limit=1`);
let gif = await fetchgif.json();
console.log(gif)
let imgurl = gif.data[0].images['fixed_height_small'].url;
return {
word: word,
imgurl: imgurl
}
}
每5秒被调用一次,并产生一个新的单词和图像?你如何用异步函数设置间隔?
setInterval(wordgif(), 5000);
此代码将调用setInterval(wordgif(), 5000);
,然后将该函数的结果传递给wordgif
。它等效于:
setInterval
由于const wordgifResult = wordgif();
setInterval(wordgifResult, 5000);
不返回值,因此调用wordgif
无效。
如果要setInterval
调用setInterval
,则只需要传递对该函数的引用作为参数:
wordgif
我已经稍微更新了您的代码。
setInterval(wordgif, 5000);
函数返回任何内容,只需在函数内部执行您想做的事情。async
文件是否可用。gif
const section = document.getElementById('main');
const text = document.querySelector('.word');
let wordurl = 'https://random-word-api.herokuapp.com/word?number=1&swear=0';
let giphyapikey = '62urPH2PxR2otT2FjFFGNlvpXmnvRVfF';
wordGIF(); // can load first gif before interval
//Setinterval
let interval;
if (interval) clearInterval(interval);
interval = setInterval(wordGIF, 5000);
//Async/await
async function wordGIF() {
let fetchword = await fetch(wordurl);
let word = await fetchword.json();
let fetchgif = await fetch(`https://api.giphy.com/v1/gifs/search?q=${word}&api_key=${giphyapikey}&limit=1`);
let gif = await fetchgif.json();
console.log('Gif available: ' + (gif && Object.keys(gif.data).length > 0));
if (gif && Object.keys(gif.data).length > 0) {
let imgurl = gif.data[0].images['fixed_height_small'].url;
text.innerHTML = word;
section.innerHTML = `<img src=${imgurl}>`;
}
}
.as-console-wrapper {
max-height: 20px !important;
}