wick3d
wick3d

Reputation: 1422

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 = '*****************';

//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?

Upvotes: 1

Views: 376

Answers (2)

Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6418

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>

Upvotes: 1

JDB
JDB

Reputation: 25855

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);

Upvotes: 1

Related Questions