javascriptfunctioneventsintervals

Issues with Handling setupIntervalButton() in refreshFetch() Function for Weather Map API


I'm currently working on a weather map API and encountering an issue with my setupIntervalButton() function when trying to use it in the refreshFetch() function. Specifically, I'm having trouble ensuring that the button is properly rendered and the interval is correctly set up before the refreshFetch() function is executed.

Here's the code for setupIntervalButton():

function setupIntervalButton(input,select,button){
    console.log('Setting up event listener'); // Debugging line
    console.log('Button element inside setup:', button); // Debugging line
    
    button.addEventListener('click', () =>{
        const intervalValue = input.value;
        const selectedInterval = select.value

        if (!intervalValue && !selectedInterval) {
            alert("Please provide numeric value and select interval type");
        } else if (!intervalValue) {
            alert("Please provide numeric value for interval");
        } else if (!selectedInterval) {
            alert("Please select interval type");
        } else{
            console.log(`Interval set to ${intervalValue} ${selectedInterval}`);
            
        }

        if(selectedInterval === "Seconds"){
            console.log(intervalValue)
            return intervalValue * 1000
        }
        else if(selectedInterval === "Minutes"){
            console.log(intervalValue)
            return intervalValue * 60000
        }
        else if(selectedInterval === "Hours"){
            console.log(intervalValue)
            return intervalValue * 60 * 60 * 1000
        }else{
            return intervalValue * 1000
        }

    })
}
function refreshFetch(){
    window.setInterval(() =>{
        fetchData()
        console.log('url fetched')
    },setupIntervalButton())

}

Issue: The main problem is that setupIntervalButton() is not rendering the button before the refreshFetch() function is executed. Consequently, the interval is not being set correctly.

You can see the JS Fiddle code here: https://jsfiddle.net/blaze92/u9zs2qy8/

Dev console Error

Questions:

1.How can I ensure that setupIntervalButton() properly sets up the interval before refreshFetch() is executed?

2.Is there a way to make setupIntervalButton() return the interval time so it can be used in refreshFetch()?


Solution

  • You call setupIntervalButton() inside setInterval(), but setupIntervalButton() doesn't return the interval value but sets up an event listener on the button, which doesn't immediately provide an interval for setInterval().

    Here is a working version, I refactored some code to make it more DRY. You do not actually need a function for the setup. I would put it all in a load event listener

    const intervalLookup = {
      Seconds: 1000,
      Minutes: 60000,
      Hours: 60 * 60 * 1000,
    };
    
    const input = document.getElementById('interval-input');
    const select = document.getElementById('interval-select');
    const button = document.getElementById('interval-button');
    
    
    // Set up the button event listener and handle interval
    const setupIntervalButton = (input, select, button) => {
      console.log('Setting up event listener');
      console.log('Button element inside setup:', button);
    
      button.addEventListener('click', () => {
        const intervalValue = input.value;
        const selectedInterval = select.value;
    
        if (!intervalValue && !selectedInterval) {
          alert('Please provide numeric value and select interval type');
          return;
        } else if (!intervalValue) {
          alert('Please provide numeric value for interval');
          return;
        } else if (!selectedInterval) {
          alert('Please select interval type');
          return;
        }
    
        console.log(`Interval set to ${intervalValue} ${selectedInterval}`);
    
        // Use the lookup table 
        const intervalMilliseconds = intervalValue * (intervalLookup[selectedInterval] || 1000); // Default to seconds
    
        console.log('Interval in milliseconds:', intervalMilliseconds);
    
        // Start the refreshFetch function since we have the interval
        refreshFetch(intervalMilliseconds);
      });
    };
    
    const refreshFetch = (intervalMilliseconds) => {
      setInterval(() => {
        fetchData();
        console.log('url fetched');
      }, intervalMilliseconds);
    };
    
    // Mock fetchData function
    const fetchData = () => {
      console.log('Fetching data from API...');
    };
    
    
    setupIntervalButton(input, select, button);
    <input id="interval-input" type="number" placeholder="Enter interval" />
    <select id="interval-select">
      <option value="Seconds">Seconds</option>
      <option value="Minutes">Minutes</option>
      <option value="Hours">Hours</option>
    </select>
    <button id="interval-button">Set Interval</button>