I have two Button (Add and mines) that I want as long as I press the Add button it constantly Adds to the center number and also the longer I press it, it adds faster
I tried setTimeout and setInterval but did not worked.
this is what I have, any suggestions?
const [amount, setAmount] = useState(0);
--
<IconButton onClick={handlePlus} className="payout__icon-button">
<Add />
</IconButton>
{amount}
<IconButton onClick={handleMinus} className="payout__icon-button">
<Remove />
</IconButton>
--
const AMOUNT_UNIT = 10000;
function handlePlus() {
let val;
val = amount + AMOUNT_UNIT;
setAmount(val);
}
function handleMinus() {
var val = 0;
val = amount - AMOUNT_UNIT;
setAmount(val);
}
}
Pseudo code:
yarn add use-long-press // or
npm install --save use-long-press
import React from 'react';
import { useLongPress } from 'use-long-press';
const Example = () => {
const bind = useLongPress(() => {
console.log('Long pressed!');
val = amount + AMOUNT_UNIT * 3;
});
return <button {...bind}>Press me</button>;
};
I find the answer myself this works really well for me and on long-press keep adding and speeding up the more you hold the button.
I use this package:
yarn add use-long-press // or
npm install --save use-long-press
these are my functions:
let myTimeout;
let longpressActive = false;
let onPressValue = 0;
let n = 200; // this is 200ms for interval func
function stopInterval() {
clearInterval(myTimeout);
if (longpressActive) {
setAmount(parseInt(onPressValue)); // bind on press data
longpressActive = false;
}
}
// for onclick func
function handlePlus() {
let val;
val = amount + AMOUNT_UNIT;
setAmount(val);
}
// for longPress func
function increment() {
longpressActive = true; //Stop the interval in essence
let myInputRef = document.querySelector(".payout__price");
onPressValue = parseInt(amount);
myTimeout = setInterval(function runIncrement() {
//Start the timeout which is really a controlled interval
if (onPressValue < props.balance) {
onPressValue += AMOUNT_UNIT;
myInputRef.innerText = onPressValue;
if (n > 60) {
n = n - 20;
}
clearInterval(myTimeout);
myTimeout = setTimeout(runIncrement, parseInt(n));
} else {
clearInterval(myTimeout);
setAmount(parseInt(props.balance));
chengeCurve(props.balance);
}
// setAmount(amount+50);
}, n); //Start the interval with an initial time of 35 milliseconds
//Now we know when the interval started, and we can
}
const Add_Long_Press_plus = useLongPress(() => {
console.log("Long pressed!");
increment();
// val = amount + AMOUNT_UNIT * 3;
});
And this is my JSX:
<IconButton
onClick={handlePlus}
onMouseUp={stopInterval}
className="payout__icon-button"
>
<Add {...Add_Long_Press_plus} />
</IconButton>
<div className="payout__price">{amount}</div>