Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

241
Views
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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

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.

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!