• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

152
Vistas
remove class only one time when add class many times

I have a following code:

btn.onclick = function() {
   toast.classList.add('showToast')
   setTimeout(function() {
      toast.classList.remove('showToast')
   }, 3100)
}

Assume at 0s I click a lot of times on button, so maybe at 3.1s I receive a lot of remove handle on toast, this is not what I expect because maybe at 3.2s I click on button one more time toast disappear immediately instead action in 3.1s. I want users could click on button as many time they want, equivalent to addClass() be handled a lot of time but removeClass() only be handled one time corresponding to the last addClass() and the last clicking. How can I do that, or maybe could you give me another way to handle this, thanks

almost 3 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

It sounds like you want to cancel any still-active timeout when the button is clicked again. In that case, you need to store the timer ID in a variable outside the function, and then call clearTimeout on that before setting the new timeout.

let timerId;
btn.onclick = function() {
   toast.classList.add('showToast')
   clearTimeout(timerId);
   timerId = setTimeout(function() {
      toast.classList.remove('showToast')
   }, 3100)
}

Note that as shown above timerId is a global variable, but this is not ideal. Ideally this code is inside some function which would mean timerId does not pollute the global scope. But that depends on information about how your code is architected that you do not show us.

almost 3 years ago · Juan Pablo Isaza Denunciar

0

create counter using setInterval()

var counterHandle;
var counter = 0;
btn.onclick = function() {
    counter = 0;
    clearInterval(counterHandle);
   toast.classList.add('showToast');
   counterHandle = setInterval(()=>{
                        counter +=1;
                        console.log(counter);
                        if(counter === 3){
                            toast.classList.remove('showToast');
                            clearInterval(counterHandle);
                        }
                        }, 1000);
   
}

when the button is pressed many times the counter will always be 0 and when the counter has a value of 3 the command will be executed

almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda