Is it possible to prevent a Timer ends?

I'm trying to show a label when a user clicks a button. I've tried to use setTimeout to achieve this, but when you click the button multiple times before the timeout ends, this don't work properly.

This is what I got:

const [cameraLabelVisible, setCameraLabelVisible] = useState(false);    
let labelTimer;

function labelVisible() {
   setCameraLabelVisible(true);
   labelTimer = setTimeout(() => {
      setCameraLabelVisible(false);
         clearTimeout(labelTimer);
      }, 1500);
   }
};

My question is: Is it posible reset the timer to the initial value (in this case 1500) by clicking the same button before the timer ends?

I want to show the label if the button is clicked multiple times before the time runs out.

Upvotes: 0

Views: 38

Answers (2)

Mackers
Mackers

Reputation: 1050

My question is: Is it possible reset the timer to the initial value (in this case 1500) by clicking the same button before the timer ends?

Yes, this can be achieved by clearing the existing timeout and creating a new timeout. This can be achieved as below:

const [cameraLabelVisible, setCameraLabelVisible] = useState(false);    
let labelTimer;

function labelVisible() {
    if(labelTimer) {
        clearTimeout(labelTimer);
    }    
    setCameraLabelVisible(true);
    labelTimer = setTimeout(() => {
       setCameraLabelVisible(false);
          clearTimeout(labelTimer);
       }, 1500);
    }
 };

I want to show the label if the button is clicked multiple times before the time runs out.

This sounds like a different issue than what you asked above. If I'm understanding you correctly, the below will allow you to click the button multiple times within 1.5 seconds, and the label appear for only that amount of time before clearing.

const [cameraLabelVisible, setCameraLabelVisible] = useState(false);    
let labelTimer = undefined;

function labelVisible() {
    setCameraLabelVisible(true);
    if(!labelTimer) {    
        labelTimer = setTimeout(() => {
            setCameraLabelVisible(false);
            labelTimer = undefined;
        }, 1500);
    }
 };

Upvotes: 0

Hao Wu
Hao Wu

Reputation: 20699

You could clear the existing timer first:

const [cameraLabelVisible, setCameraLabelVisible] = useState(false);
let labelTimer;

function labelVisible() {
    setCameraLabelVisible(true);

    // clear the timer if there's another timer running
    if(labelTimer) clearTimeout(labelTimer);

    labelTimer = setTimeout(() => {
        setCameraLabelVisible(false);
    }, 1500);
}

Upvotes: 1

Related Questions