[英]How do you call a function with arguments repeatedly with setInterval()?
[英]How do you call a asynchronous function using setInterval?
我得到一個隨機詞,然后用這個詞生成一個 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 秒調用一次並生成一個新單詞和圖像? 你如何用異步函數設置間隔?
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; }
<div id="main"></div> <div class="word"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.