我得到一个随机单词,然后使用该单词生成GIF。 我的代码在这里仅运行一次。我希望它生成另一个单词并获得另一个图像,而无需刷新浏览器。
因此,我通过传递使用setInerval();
获取图像的函数来使用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
}
}
据我所知
setInterval(wordgif(), 5000);
每5秒被调用一次,并产生一个新的单词和图像?
如何使用异步函数设置Interval?
答案 0 :(得分:1)
setInterval(wordgif(), 5000);
此代码将调用wordgif
,然后将该函数的结果传递到setInterval
。等效于:
const wordgifResult = wordgif();
setInterval(wordgifResult, 5000);
由于wordgif
不返回值,因此调用setInterval
并没有实际效果。
如果您希望setInterval
调用wordgif
,则只需传递对该函数的引用作为参数:
setInterval(wordgif, 5000);
答案 1 :(得分:1)
我已经对您的代码进行了一些更新。
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;
}
<div id="main"></div>
<div class="word"></div>