Caquibf
Caquibf

Reputation: 59

Can I integrate two timers in the same one?

I'm using the react-native-countdown-circle-timer snack example provided. With it, I want to have two timers in one, or one after the other in an unlimited sequence.

What I mean is to have the first timer count (and when it finishes) followed by a second timer (different time/colour) and then the first one again switching indefinitely.

import * as React from 'react';
import { Text, View, StyleSheet, Animated, Button } from 'react-native';
import Constants from 'expo-constants';
import { CountdownCircleTimer } from 'react-native-countdown-circle-timer';


export default function App() {
  const [isPlaying, setIsPlaying] = React.useState(true)
  return (
    <View style={styles.container}>
      <CountdownCircleTimer
        isPlaying={isPlaying}
        duration={10}                  // could I have 2 different durations here??
        colors={[
          ['#FFFF00', 0.4],               //Colour 1
          ['#0000ff', 0.4],               //Colour 2
        ]}
        onComplete={() => [true]}
    >
      {({ remainingTime, animatedColor }) => (
        <Animated.Text style={{ color: animatedColor, fontSize: 40 }}>
          {remainingTime}
        </Animated.Text>
      )}
    </CountdownCircleTimer>
    <Button title="Toggle Playing" onPress={() => setIsPlaying(prev => !prev)}/>
  </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  }
});

Upvotes: 0

Views: 219

Answers (1)

Darshan J
Darshan J

Reputation: 239

You can create a switch between durations after onComplete callback is called on react-native-countdown-circle-timer.

Refer to this expo code below. It has a working example of the solution.

https://snack.expo.dev/@darshan09200/stackoverflow-question-no-69081296

As per the docs, If you want to reset time after the component has been mounted

key={value} Whenever this value is updated the timer component takes the new value of the duration

const duration = [10, 20];

You can specify any number of duration in this array.

setTimeIndex((index) => {
    let newIndex = index + 1;
    if (newIndex >= duration.length) {
        newIndex = 0;
    }
    return newIndex;
});

This will evaluate the next index from the array of duration. If the index exceeds the length it will start from 0, which will call the infinite loop.

Upvotes: 2

Related Questions