Codementor Events

Building a Digital Timer with Redux

Published Apr 10, 2017
Building a Digital Timer with Redux

Redux is a state-management tool for front-end apps. It's declarative api helps developers build complex apps in a very modular way. Let's checkout how we can build a simple timer using Redux.

Installing Redux

Let's first include redux from a cdn and add it to our index.html page


<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/redux@^3.5.2/dist/redux.min.js"></script>
  <script src="main.js"></script>
  <meta charset="utf-8">
  <title>Redux timer</title>
</head>
<body>
  <p id="timer"></p>
</body>
</html>

Setting up a Redux store

Now, let's grab the createStore function from Redux and initialize our store. Our store needs a reducer function, which will be used to generate state on the fly. Let's add that in as well. Now, since we intend to build a timer, it's good enough if we just have a number as our state value and keep incrementing it with actions.
We will put all of our JavaScript in main.js.


const { createStore } = Redux;

const store = createStore(counterReducer);

function counterReducer(state, action){
  // initially state is undefined, so let's return 0 when the 
  // store is first created
  if(typeof state === 'undefined'){
    return 0;
  };
  // when this actions is dispatched, increment state
  if(action.type === 'INCREMENT_TIMER'){
    return state + 1;
  }
  return state;
}

Now, our store is ready!

Dispatch it!

Now that our store is all wired in, let's fire our action.


const { createStore } = Redux;

const store = createStore(counterReducer);

function counterReducer(state, action){
  if(typeof state === 'undefined'){
    return 0;
  };
  if(action.type === 'INCREMENT_TIMER'){
    return state + 1;
  }
  return state;
}
console.log('increment timer')
store.dispatch({   
  type : 'INCREMENT_TIMER'
})

Now, this will only fire the action once. Let's wrap it in a setInterval and make it execute once every second. Our code becomes:


const { createStore } = Redux;

const store = createStore(counterReducer);

function counterReducer(state, action){
  if(typeof state === 'undefined'){
    return 0;
  };
  if(action.type === 'INCREMENT_TIMER'){
    return state + 1;
  }
  return state;
}

setInterval( function() {
   console.log('increment timer')
   store.dispatch({
     type : 'INCREMENT_TIMER'
   })
}, 1000 )

Update view

If we look at the index.html page, we have a "p#timer" in place to show the value of the timer. Let's write a simple script to update the timer for when the state of our app changes. We can do that using the store.subscribe function, which is fired each time the value of the state in redux changes.


store.subscribe( function() {
    document.getElementById("timer").innerHTML = store.getState()
})

This is all we need. Our main.js file should now look like this.


const { createStore } = Redux;

const store = createStore(counterReducer);

function counterReducer(state, action){
  if(typeof state === 'undefined'){
    return 0;
  };
  if(action.type === 'INCREMENT_TIMER'){
    return state + 1;
  }
  return state;
}

setInterval( function() {
   console.log('increment timer')
   store.dispatch({
     type : 'INCREMENT_TIMER'
   })
}, 1000 )

store.subscribe( function() {
    document.getElementById("timer").innerHTML = store.getState()
})

You should be able see the view being updated each time the timer increases now.

Formatting the view

The last part of this app is to format the view to show seconds, minutes, and hours, instead of a huge number like 115. Let's plug that logic in:


store.subscribe( function() {
    const totalSecondsPassed = store.getState(),
           totalMinutesPassed = Math.floor(totalSecondsPassed/60),
           hours = Math.floor(totalMinutesPassed/60),
           minutes = totalMinutesPassed % 60,
           seconds = totalSecondsPassed % 60;
  
   document.getElementById("timer").innerHTML = `${hours} hours ${minutes} minutes ${seconds} seconds`
    
})

There we go, we now have our first redux timer app built.

Screen Shot 2017-04-03 at 12.15.02 PM.png

Check out the demo here.

If you have any questions or comments, let me know!

Discover and read more posts from Bhargav
get started
post comments3Replies
Juraj Dobrik
7 years ago

Dude, this can be oneliner in PHP writting JS.

taufiq ahmed
8 years ago

Thank you for the simple intro. This is the best way to understand redux.

Bhargav
7 years ago

Glad you liked it!