I am working with a React Native button in which i am calling a function. But i want to call the function only after 250 ms and when the user leaves the button which means when the onPressOut is called. How can i do that. Currently it's like this:
const onChangeCurtain = () =>{
setActive(!active);
onPressItem();
}
const onLongPress = () => {
setActive(false);
}
return (
<Container
onPress={onChangeCurtain}
onPressOut={onLongPress}
/>
)
Now onChangeCurtain gets called immediately and onLongPress gets called when the user leaves the button. But i don't want onLongPress to be called if pressed for less than 250 ms. It should be called only if it gets pressed for more than 250 ms. How can i do that?
You can use event listeners on button like onKeyDown and onKeyUp.
In onKeyDown start setTimeout which will perform something after 250ms
And in onKeyUp clear this interval so it will not trigger if user did not pressed guver button long enough.
import * as React from 'react';
export default function App() {
let downTimer = null;
const onMouseDown = () => {
clearTimeout(downTimer);
downTimer = setTimeout(function() {
alert('Mouse down > 250 ms');
}, 250);
}
const onMouseUp = () => {
clearTimeout(downTimer);
}
return (
<button onMouseUp={ onMouseUp } onMouseDown={ onMouseDown }>asd</button>
);
}