Reputation: 1968
I want to know how to use setTimeout()
method. Basically, I want to click on the element after some seconds and after that perform something.
So My code is as below,
class SomeComponent extends React.PureComponent {
on_first_render = () => {
this.somemethod_called();
setTimeout(() => {
this.props.handle_click(52, 16);
},0);
setTimeout(() => {
this.props.handle_click(522, 352);
}, 0)
setTimeout(() => {
const input = document.querySelector('input[type=text]
[name=somename]');
input && input.blur();
}, 700);
As seen from above code, same handle_click()
method is called in two setTimeout()
methods and after 7 seconds I search for input element in the document and remove focus from it.
I feel this is clumsy and not right approach... Could someone let me know how to do it in another way which is not repeated like this.
Thanks.
Upvotes: 2
Views: 165
Reputation: 101
Rather than using setTimeOut, you can use debounce to make delay in any operation.
var SearchBox = React.createClass({
componentWillMount: function () {
this.delayedCallback = _.debounce(function (event) {
// "event.target" is accessible now
}, 1000);
},
onChange: function (event) {
event.persist();
this.delayedCallback(event);
},
render: function () {
return (
<input type="search" onChange={this.onChange} />
);
}
});
for more detail go through this module https://www.npmjs.com/package/react-debounce-input
Upvotes: 0
Reputation: 169022
As things are, your setTimeout
s aren't waiting for anything; you're queuing three timeouts that will resolve after 0, 0, and 700 msecs respectively.
Although I'm not quite sure what you're after in the end, or if you're doing things in a very idiomatic React way, I'd suggest using async
/await
and a "delay" helper function:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
const onFirstRender = async () => {
this.somemethod_called();
await delay(100);
this.props.handle_click(52, 16);
await delay(100);
this.props.handle_click(522, 352);
await delay(700);
const input = document.querySelector("input[type=text][name=somename]");
if (input) {
input.blur();
}
};
Upvotes: 3