I want to show the current time(MM/DD/YY hh:mm:ss) in react native app like a clock, and get update every seconds, I tried using new Date() and set it in state, but the time don
I would recommend to prefer using setTimeout
instead of setInterval
, indeed, the browser may be overhelmed by heavy processing and in that case you would probably prefer updating the clock less often instead of queuing several updates of the state.
With setTimeout
it is also a bit easier to leverage the Page Visibility API to completely stop the clock when the page is hidden (see https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API).
export default class MyClock {
constructor(props) {
super(props);
this.state = {
currentTime: Date.now(),
};
}
updateCurrentTime() {
this.setState(state => ({
...state,
currentTime: Date.now(),
}));
this.timeoutId = setTimeout(this.updateCurrentTime.bind(this), 1000);
}
componentWillMount() {
this.updateCurrentTime();
document.addEventListener('visibilitychange', () => {
if(document.hidden) {
clearTimeout(this.timeoutId);
} else {
this.updateCurrentTime();
}
}, false);
}
componentWillUnmount() {
clearTimeout(this.timeoutId);
}
}