I'm working on a simple weather map that changes the background image depending on the current weather status. However, I've noticed that there is a delay in changing the image when the weather status changes. I'm wondering if this delay is due to how my code is structured or if there is another issue causing it. Can you suggest ways to improve the performance and make the image change faster?
form.addEventListener("submit", getData);
function getData(e){
e.preventDefault();
const link = 'http://api.openweathermap.org/data/2.5/weather?q=';
const cityInput = input.value;
const apiId = '&appid=12345667889&units=metric';
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = ()=>{
if (xhr.readyState == 4 && xhr.status == 200) {
const object = JSON.parse(xhr.response);
country.textContent = object.sys.country;
city.textContent = cityInput;
humid.textContent = object.main.humidity + "%";
temp.textContent = object.main.temp;
wind.textContent = object.wind.speed + "mph";
let snrise = object.sys.sunrise;
let snset = object.sys.sunset;
let dtrise = new Date(snrise*1000);
let dtset = new Date(snset*1000);
let risehrs = dtrise.getHours();
let sethrs = dtset.getHours();
let risemnts = "0" + dtrise.getMinutes();
let setmnts = "0" + dtset.getMinutes();
sunrise.textContent = risehrs + ' : ' + risemnts.substr(-2) ;
sunset.textContent = sethrs + ' : ' + setmnts.substr(-2);
const weatherName = object.weather[0].description.slice(0,17);
status.textContent = weatherName;
switch(true){
case weatherName.includes("rain"):
bgImg.src = "./images/rain.jpg";
break;
case weatherName.includes("clouds"):
bgImg.src = "./images/clouds.jpg";
break;
case weatherName.includes("snow"):
bgImg.src = "./images/snow.jpg";
break;
case weatherName === "mist":
bgImg.src = "./images/mist.jpg";
break;
// Add other cases here for different weather conditions
default:
bgImg.src = "./images/pexels-photo-39811.jpg";
}
}
}
xhr.open('GET', link + cityInput + apiId, true);
xhr.send();
}