react-native-timer
We follow [breaking].[feature].[fix] versioning
npm install --save react-native-timer
A better way to manage timers in react-native with ES6 components, using WeakMap.
Version 1.3.6
-
Often you need to do things like show a message for a few seconds, and then hide it, or run an operation again and again at a specific interval. These things will usually happen inside a React Component, and will start after a component has mounted. So, you really cannot just do a
setTimeout(fn, 2000)
for non trivial things. You need to do athis.timer = setTimeout(fn, 2000)
, and thenclearTimeout(this.timer)
incomponentWillUnmount
. -
When a component unmounts, these timers have to be cleared and, so that you are not left with zombie timers doing things when you did not expect them to be there.
-
React, right now, offers a solution using the
react-native-timer-mixin
for this. However, mixins are not part of ES6-7 standard, and probably will never be as they get in the way of good software design. And this brings us to the package in question,react-native-timer
. -
With
react-native-timer
, you can set different timers, liketimeout
,interval
etc in the context of a react component, and unmount all of them when the component unmounts, at context level.
Generic API:
const timer = ; // timers maintained in the Map timer.timeoutstimer;timer;timer; // timers maintained in the Map timer.intervalstimer;timer;timer; // timers maintained in the Map timer.immediatestimer;timer;timer; // timers maintained in the Map timer.animationFramestimer;timer;timer;
Mostly, using timers is a pain inside react-native components, so we present to you Contextual Timers. API:
timer;timer;timer // clears all timeouts for a contexttimer; timer;timer;timer; // clears all intervals for a contexttimer; timer;timer;timer; // clears all immediates for a contexttimer; timer;timer;timer; // cancels all animation frames for a contexttimer;
Example Below:
const timer = ; Component state = showMsg: false ; { timer; } { this; } { return <View style=flex: 1> <TouchableOpacity onPress= > <Text>Press Me</Text> </TouchableOpacity> thisstateshowMsg ? <Text>Hello!!</Text> : null </View> }
PS: Kinda not a best practice, but const t = require('react-native-timer')
can cut down some typing.
Also, this lib can be used in browsers too, but will focus on them when I am working with them.