$(document).on("click", ".searchbutton", function(e){
var city = $("#searchbar").val()
event.preventDefault();
setInterval(function(){
var hdate = new Date()
var offset = 0 - hdate.getTimezoneOffset()/60
var hmin = hdate.getMinutes()
var hsec = hdate.getSeconds()
var diff = Math.round(Long/15) - offset
if((hdate.getHours() diff) > 23){
disphour = (hdate.getHours() diff) - 24
var formattedNumberh = ("0" disphour).slice(-2)
$("#hour").text(formattedNumberh)
}
else if((hdate.getHours() diff) < 0){
disphour = 24 (hdate.getHours() diff)
var formattedNumberh = ("0" disphour).slice(-2)
$("#hour").text(formattedNumberh)
}
else{
disphour = hdate.getHours() diff
var formattedNumberh = ("0" disphour).slice(-2)
$("#hour").text(formattedNumberh)
}
var formattedNumberm = ("0" hmin).slice(-2)
var formattedNumbers = ("0" hsec).slice(-2)
$("#minute").text(formattedNumberm)
$("#second").text(formattedNumbers)
}, 1000)
})
This function is executed when a city name is put inside an input field and a button is pressed; it displays the time in that city.
When I put a city in the input field after refreshing the page, it works fine. However, when I put another city right after, the displayed hour fluctuates between the hour of the previous city and the new one.
I'm not sure what the problem is.
CodePudding user response:
You never clear the interval. So each "search" creates a new interval, and each interval keeps running and doing what it was told to do.
For example, you might track the "current interval" in a variable, and use that variable to clear the interval before creating a new one:
// track the interval
var currentInterval = -1;
$(document).on("click", ".searchbutton", function(e){
// clear the current interval
if (currentInterval > 0) {
clearInterval(currentInterval);
}
var city = $("#searchbar").val();
event.preventDefault();
// set the new interval
currentInterval = setInterval(function(){
//...
}, 1000);
});