Skip to content

Instantly share code, notes, and snippets.

@carlows
Last active September 23, 2016 21:08
Show Gist options
  • Save carlows/6914a71bd6ee6320026734502220ec11 to your computer and use it in GitHub Desktop.
Save carlows/6914a71bd6ee6320026734502220ec11 to your computer and use it in GitHub Desktop.

Author

Carlos Martinez

Disclaimer

This spec is completed

Problem Overview

Whenever the timer is started and the user reloads the timer page, there's a delay between the initial rendering and the update to the local state of the timer causing it to display 0 seconds:

gif

(I'm reloading the page)

Goals

Our goal is to display the correct current time of the timer as soon as the component is rendered and avoid the delay to show the state.

Background

When the timerform component gets mounted, it's state is being set to Date.now():

this.state = {
  startTimeInMilliseconds: Date.now(),
  timeElapsed: 0
};

This causes the initial render of the component to calculate the state based on the current time, and this is why it displays 0 seconds initially.

After the component gets mounted, the componentDidMount checks the localState to see if a timer was running last time the user was on the page:

componentDidMount() {
  let timerState = localStorage.getItem('timerState');

  if (timerState) {
    // update state
  }
}

The tick function (the one that is being executed with the inverval) updates the state each second calculating the time elapsed:

tick() {
  // calculates time elapsed based on the current state
  // updates the state
}

Functional spec

Our problem here, is that the tick function in the initial render uses uses the state set in the constructor, and because the interval runs each second, we have a 1 second delay between the initial rendering and the update of the values

To solve this I'm going to execute the tick function with the state retrieved from the localState:

componentDidMount() {
  let timerState = localStorage.getItem('timerState');

  if (timerState) {
    this.tick(timerState.startTimeMs);
  }
}

And add the parameter to the tick function:

tick(startTime) {
  // calculate time based on startTime if available
  // update state
}
@orlando
Copy link

orlando commented Sep 23, 2016

LGTM

@orlando
Copy link

orlando commented Sep 23, 2016

again this is a functional spec not a technical

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment