Workshop › Minesweeper › Step 25 of 26

The best time

What we are doing

The best (lowest) time is saved in localStorage. Two traps: "best" means smaller, so the comparison is <; and "no best yet" must be null, not 0, because a very fast win really can take 0 whole seconds.

```js
// null means "no best time yet"; 0 would be a real (very fast) time.
const saved = localStorage.getItem('mines-best')
let best = saved === null ? null : Number(saved)

  const seconds = Math.floor((endTime - startTime) / 1000)
  if (best === null || seconds < best) {
    best = seconds
    localStorage.setItem('mines-best', best)
  }

    ctx.fillText(state === 'won' ? 'You win! Best: ' + best + 's' : 'Boom! Click to retry', canvas.width / 2, TOP / 2)
```

What it means

Your turn

  1. Under let now = 0, write the comment, saved and best.
  2. At the end of win, write the seconds line and the if block.
  3. In draw, change 'You win!' to 'You win! Best: ' + best + 's'. Press Run.

Skills: Game states

All steps

  1. A grid of cell objects
  2. The canvas and the pen
  3. Draw the field
  4. Draw every frame
  5. Neighbours
  6. Mines, but not under the first click
  7. Shuffle the candidates
  8. Count the mines around
  9. Open a cell
  10. Open cells look different
  11. Coloured numbers
  12. Click to open
  13. Stepping on a mine
  14. Show the mines
  15. Flood fill
  16. Flags with the right button
  17. A flag protects its cell
  18. Draw the flags
  19. Mines left
  20. Winning
  21. The end and a new game
  22. What time is it?
  23. The clock
  24. Stop the clock
  25. The best time
  26. Build it yourself: wrong flags