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():

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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
}
})
}
</code>
<code>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 } }) } </code>
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
        }

    })
}
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>function refreshFetch(){
window.setInterval(() =>{
fetchData()
console.log('url fetched')
},setupIntervalButton())
}
</code>
<code>function refreshFetch(){ window.setInterval(() =>{ fetchData() console.log('url fetched') },setupIntervalButton()) } </code>
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/

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()?

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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);</code>
<code>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);</code>
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);
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><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></code>
<code><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></code>
<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>

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật