Stopping setTimeout when leaving the current page: Is it possible?

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;

Answer №1

In reference to the documentation found at https://reactjs.org/docs/hooks-reference.html#cleaning-up-an-effect, it is advised that you can use the return statement within the useEffect hook to perform clean up when the component is unmounted.

Therefore, as a precautionary step, consider adding the following line at the end of your useEffect function:

return () => clearTimeout(timer);

This will ensure that the timeout is properly canceled when the component is no longer in use.

Answer №2

After some research, it seems like I've come across a potential solution for the issue you're facing.

const FunctionalComponent = () => {
 React.useEffect(() => {
   return () => {
     console.log("Bye");
   };
 }, []);
 return <h1>Bye, World</h1>;
};

I discovered this information on -

One useful tip is to incorporate clearInterval() within the useEffect().

The useEffect() function functions similarly to the traditional componentWillUnmount(). It serves as an ideal location to implement clearInterval() before navigating to a new page.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing dual functions within the onChange event handler in React

I have a situation where I need to pass a function from a parent component to a child component through the onChange event, as well as another function in the child component to update its own state. How can I achieve this? Parent export function Fruits() ...

Creating dropdown options with JSON and Angular

This dilemma has been causing me no end of distress. I am trying to figure out how to populate options for a select tag from a JSON object using Angular. Here is a snippet of the code: <select id="cargo" ng-model="cargo.values.cargoList"> <op ...

Here's a unique rewrite: "Tips for success in passing a React component as a child and dynamically adding props

I am dealing with an object that contains various items such as Milk, Bread, and Tea along with their corresponding components. const obj = { name: 'Milk', component <Milk />; name: 'Bread', component <Bread />; name: &ap ...

Discover the secret to efficiently validating multiple email addresses with a single validation schema field in Formik!

My customer form requires two pieces of information. Customer name Customer Emails (which can be multiple) Next to the email field, I have added an 'add' button that allows users to add more emails to the form. Now, I need to validate each emai ...

Filtering input that is compatible with Firefox

Attempting to restrict certain special characters (excluding "_" and "-") from being used in a text input field has been a bit of a challenge. I initially tried using regex filtering by pattern, but it didn't work as expected. Then I turned to dynami ...

Using React Native to pull data in my app from mySQL database

In my coding journey, I encountered a local database managed through myPHPadmin, and implemented the following code snippet: // Here is a glimpse into the routes.js file! const express = require('express'); const bodyParser = require('body- ...

What could be causing this Vue.js component to show the body of a function instead of its intended output?

I'm currently developing a small Todo App using Vue 3 for the front-end and Slim 3 for the back-end (API). Within App.vue, you'll find: <template> <div id="app"> <Header title="My todo list" :un ...

Toggle class to a div upon clicking menu item

Seeking assistance with jQuery to develop a video player featuring a sub menu for displaying various content options upon selection. Here is a snapshot of the frontend design: view image Upon clicking on 'video' or 'audio', a distinct ...

Shades of Grey in Visual Studio Code

Whenever I use VSC, I notice these odd grey boxes that appear in my editor. They seem to be dynamic and really bother me. Interestingly, switching to a light theme makes them disappear. However, I prefer using a dark theme and haven't been able to fin ...

The functionality of the WordPress Contact Form 7 Plugin becomes erratic when integrated into dynamically loaded AJAX content

I am currently facing a challenge with integrating the WordPress Contact Form 7 Plugin into a website I have built on WordPress. The theme of the site utilizes jQuery to override default link behavior and AJAX to load pages without refreshing the entire pa ...

Navigating through the fetch API request when using express js

I'm looking to use the fetch API to send requests and have those requests handled by Express JS. In my setup, I've put together server.js (Express JS), index.html (home page), and signin.html (sign-in page). index.html <!DOCTYPE html> < ...

JavaScript returns the value 'undefined' when a function variable is used with an array of objects

Here is an example of an array of objects: var theArray = [ {theId:'1', num: 34}, {theId:'2', num: 23}, {theId:'5', num: 26} ]; This function successfully loops through the array: function printValues() { va ...

Tracking a user's path while redirecting them through various pages

Recently, I created a website with a login page and a home page using nodejs, javascript, and html. The client side sends the entered username and password to the server, which then replies based on the validation result. During navigation between pages, h ...

Hierarchy in CSS: The battle between author and user styling

Following a hierarchy of precedence: User agent declarations User normal declarations Author normal declarations Author important declarations User important declarations The CSS specification distinguishes between author and user: Author. The author s ...

Positioning Data Labels Outside of Pie or Doughnut Charts in Chart.js

I am currently working on a large-scale project and I am in need of a way to position the labels outside of pie charts or doughnut charts. I came across a plugin called outerLabels on GitHub which seems to be the perfect solution for what I need, but I am ...

Attempting to retrieve the value of "id" using a "for...of" loop

I am seeking assistance with my auditTime function. In the loop using "for . . of", each element of the div HTML collection with the class name "time-block" should be iterated through, and the number value of that div's id should be assigned to the va ...

What causes the sub-menus to move even when they are set to position: absolute?

The sub-menu items under the about link appear to be slightly shifted from the left, despite setting it with position: absolute; left: 0px. I aim to have all menu items (including sub-menus) perfectly overlapped. Below is the code snippet: <html> & ...

Minimizing redundancy in React Redux application callbacks

Trying to grasp the concept of using react and redux together has been quite challenging for me. The issue I am facing is that as my app becomes more complex, it seems like there is a lot of repetitive code to deal with. For instance, let's consider ...

What is the process for transforming a Typescript source file into JavaScript?

I have a basic HTML file with a script source set to index.ts. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge ...

Creating a Custom Class for a Custom Button in TinyMCE 4 Using addButton()

Is there a way to add a custom class to a custom button using the addButton() function in TinyMCE? Here is an example: editor.addButton('keywords', { text: 'Insert Keywords', class: 'MyCoolBtn', ...