Search code examples
reactjsreduxreact-reduxredux-thunk

Redux Thunk - Is it possible to cancel a setTimeout


I want to implement a notification system that creates a message after the user makes an API request. However I don't want to create multiple messages on the screen and would want to cancel previous messages and only show the most recent one. Recently learned about thunks and their use and was wondering is it possible to cancel a setTimeout or would there be a better way to implement it.

This is the thunk message I was planning on using.

export const startNotification = (message) => {
  return dispatch => {
    setTimeout(() => {dispatch(notificationMessage(message))}, 5000);
  };
};

I am unsure on the approach to resolve this. One method I was thinking of was updating my reducer to deal with multiple messages but it seems like that'll make the reducer too complicated. Ideally I would want to cancel any existing timeouts and then call function again. Is there a way to implement this or is there a better alternative to what I want to achieve?


Solution

  • setTimeout() returns a handle that you can cancel with clearTimeout(), so that's one option.

    However, I'd recommend clearing previous messages in the reducer. Whenever your notifications reducer receives a new message it can just get rid of any other messages.

    If you do end up using clearTimeout(), you can find more information about it at https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout