Good evening, I am looking for advice on how to cancel a setTimeout function when a user navigates to other pages (for example, by clicking other links or pressing the back button in the browser, but not by changing tabs). I have attempted to use the window event "unload", but it doesn't seem to work as expected.
My application is a standard countdown timer that automatically redirects to an assigned page when it reaches 0. However, for specific reasons, I need to disable this automatic redirect if the user clicks on other links while the countdown is in progress. Thank you for your assistance.
import React, { useEffect } from 'react';
import {useHistory} from "react-router-dom";
const SucessPurchaseSubmit = () => {
const history = useHistory();
const navigateTo = () => history.push("/house-catalog");
useEffect(() => {
const time = document.querySelector(".time");
let count = 10;
var timer;
// Automatically navigate to full catalog after 10 seconds
function countToNavigate(){
clearTimeout(timer);
time.innerHTML = count;
if (count === 0) {
navigateTo();
}
count -= 1;
timer = setTimeout(countToNavigate, 1000)
}
countToNavigate();
window.addEventListener("unload", () => {
clearTimeout(timer);
})
})
return (
<section className="success-purchase-submit">
<h1>Thank you so much for your information</h1>
<h3>One of our consultants will contact you very shortly</h3>
<h5>In the mean time, we will back to Full Catalog automatically after:</h5>
<h5 className="time">10</h5>
</section>
);
};
export default SucessPurchaseSubmit;