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