简体   繁体   中英

How do you call a asynchronous function using setInterval?

I get a random word and then use the word to generate a GIF. My code here runs for only one time. I want it to generate another word and get another image without refreshing the browser.

So,I have used setInerval(); by passing the the function that gets the image using 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
    }
}

As far as my understanding shouldn't setInterval(wordgif(), 5000); be called every 5 seconds and generate a new word and image? How do you setInterval with asynchronus function?

setInterval(wordgif(), 5000);

This code will call wordgif , then pass the result of that function to setInterval . It is equivalent to:

const wordgifResult = wordgif();
setInterval(wordgifResult, 5000);

Since wordgif doesn't return a value, calling setInterval has no real effect.

If you want setInterval to call wordgif , then you need only pass a reference to the function as the argument:

setInterval(wordgif, 5000);

I've updated your code a little bit.

  • You should clear the interval regularly.
  • You don't need to return anything from the async function, just do what you want to do inside the function.
  • Must check if the gif file available before rendering it.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM