Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
Alternative to global variable when using clearTimeout & setTimeout

EDIT I used the wrong term in the title and question. I did not mean a global variable, but to instead declare timeoutID inside of the showNotification function.

I'm on my first week of testing Redux. I'm wondering if there is a more elegant / less hacky solution to using a glodal variable for the timeoutID? clearTimeout is used to guarantee that the last added notification is always shown for the full desired time, even if it would be added before the previous notification was set to "empty".

actionCreator.js

import { addQuote } from "./addQuote"
import { showNotification } from "./showNotification"

export const actionCreator = (quote, time) => {
  return dispatch => {
    dispatch(addQuote(quote))
    dispatch(showNotification(quote, time))
  }
}

showNotification.js

let timeoutID = null

export const showNotification = (newQuote, time) => {

  const message = `A new quote by ${newQuote.author} was added.`
  return dispatch => {
    dispatch({ type: 'SHOW_NOTIFICATION', data: message })

    clearTimeout(timeoutID)
    
    timeoutID = setTimeout(() => {
      dispatch({ type: 'SHOW_NOTIFICATION', data: '' })
    }, time * 1000)
    
  }
}

notificationReducer.js

const initState = {
  notification: ''
}

const notificationReducer = (state=initState, action) => {
  switch (action.type) {
    case 'SHOW_NOTIFICATION':

    const message = action.data
      return {
        ...state,
        notification: message
      }

    default:
      return {
        ...state
      }
  }
}

export default notificationReducer
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It's not global, it's a closure, and that's one of the core principles in a module world (which was invented to circumvent having to make use of the global namespace!).

If it were global you could use the variable in any other JS file without ever explicitly importing it.

In actionCreator.js, which does import { showNotification } from "./showNotification", try to console.log(timeoutID) and you'll get undefined.

Closures are really nothing complicated; it just means that any function when declared will "remember" any local variables that were known ("in scope" is the more technically correct term for "known") at the point of the function's declaration, no matter when the function is called, or who calls it. Those variables known to a function via this mechanism are called closures.

There is not only nothing wrong with programming this way; it moreso is state of the art and in contrast to other far more verbose and lengthy solutions like passing parameters around, the most elegant way to solve the problem.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda