I want to run it again after the end of setInterval, but after running it in Ajax, it starts showing strange numbers. It is clear in the picture below.
When I run the page, setInterval works, but when the time expires and I make an ajax request, it doesn't start decrementing again. Please help me.
All my code is.
const TIME_LIMIT = 10; // 10 second
let timePassed = 0;
let timeLeft = TIME_LIMIT;
let timerInterval = null;
function onTimesUp() {
clearInterval(timerInterval);
}
function startTimer() {
timerInterval = setInterval(() => {
timePassed = timePassed = 1;
timeLeft = TIME_LIMIT - timePassed;
document.getElementById("dividname").innerHTML = formatTime(
timeLeft
);
if (timeLeft === 0) {
onTimesUp();
}
}, 1000);
}
function formatTime(time) {
const minutes = Math.floor(time / 60);
let seconds = time % 60;
if (seconds < 10) {
seconds = `0${seconds}`;
}
return `${minutes}:${seconds}`;
}
And this is my Ajax code that sends the request and success is executed, but setInterval is not executed correctly. (I have put the picture below).
$.ajax({
type: 'POST',
url: aw_ajax_url,
dataType: 'json',
data: {
'action': 'acttionname',
},
success: function (data) {
onTimesUp();
document.getElementById("dividname").text = timeLeft;
startTimer();
}
});
Image after restarting Ajax: It is sad
Final note: I want setInterval to restart every time
I make an Ajax request. Thank you for your help.
CodePudding user response:
I think you forgot to reset both timeLeft and timePassed. Also, setting innerText is unnecessary since it's already handled by the timer. It should be something like this:
success: function(data) {
onTimesUp();
timePassed = 0;
timeLeft = TIME_LIMIT;
startTimer();
}