Search code examples
javascriptfetchbackground-process

Is it possible to run a script on my frontend, in the background, that'll update a variable every few minutes?


I have a form with a drop down select input field. this select field's options should ideally be up to date with the backend.

I have a script in the backend which updates a list of options every 5 minutes.

As an initial trivial solution I've added an 'on focus' event listener to the select filed which fires a fetch request and updates the drop down with the returned list.

This off course introduces a small delay, and is overall unpleasant to use when I have menus that react in dependence to the first drop down.

Is there a way to run a script on the frontend background that'll fetch the options to a variable and update the drop down every few minutes?

(I'm using vanilla JS)

Thanks a lot in advance!


Solution

  • You could do something like this to update every 10 seconds:

    function getOptions(){
      setInterval(async function(){
        const response = await fetch(/*whatever you want to fetch*/);  
        const options = await response.text();
        /*use the data here*/
      }, 10000);
    }
    

    You could also do a function which fires itself when it is done fetching the data using fetch().then() which I think is to be preferred here.

    fetch() can use .then(), .catch() and .finally() so you could run the function again at .finally().