Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda