0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

VanJSでクリックカウンターを作ってみた

Posted at

はじめに

先日Youtubeを見ていたら16連射でお馴染みの高橋名人が出てたので、私も連射に挑戦してみたいと思いクリックカウンターのアプリを作ってみました。10秒の制限時間でクリック数を計測して、1秒間にクリックした回数の平均値が表示されるようにしました。リポジトリは公開しているので、VanJS初学者の方などは参考にしてみてください。

デモ

ちなみに私の最高記録は8.60です😢

リポジトリ

コード

src/main.ts
import van from 'vanjs-core'

import { useTimeLeft } from './useTimeLeft'

const TIME_LEFT = 10

function App() {
  const { h1, div, p, button } = van.tags

  // クリック数
  const count = van.state(0)
  // 残り時間、アクティブかどうか、スタートとリセットの関数オブジェクト
  const [timeLeft, isActiveInterval, handler] = useTimeLeft(TIME_LEFT)

  // 一秒間にクリックした回数の平均値
  const clicksPerSecond = van.derive(() => {
    return timeLeft.val === 0 ? count.val / TIME_LEFT : 0
  })

  // クリック数と残り時間をリセット
  const handleReset = () => {
    count.val = 0
    handler.reset()
  }

  return div(
    { class: 'click-counter' },
    h1({ class: 'title' }, 'VanJS Click Counter'),
    p({ class: 'text' }, 'Clicks: ', count),
    p({ class: 'text' }, 'Time Left: ', timeLeft, ' seconds'),
    p({ class: 'text' }, 'Average Clicks Per Second: ', () =>
      timeLeft.val === 0 ? clicksPerSecond.val.toFixed(2) : '',
    ),
    div(() =>
      isActiveInterval.val
        ? // アクティブの時はクリックでカウントを増やせるように
          button(
            {
              class: 'action-button',
              onclick: () => count.val++,
            },
            'Click',
          )
        : // アクティブでない時は計測スタートできるように
          button(
            {
              class: 'action-button',
              onclick: () => handler.start(),
              disabled: () => timeLeft.val === 0,
            },
            'Start',
          ),
    ),
    button(
      {
        class: 'reset-button',
        disabled: isActiveInterval,
        onclick: () => handleReset(),
      },
      'Reset',
    ),
  )
}

van.add(document.getElementById('app')!, App())

useTimeLeft.tsはReactのカスタムフックのようなものです。以前VanJSでカスタムフックを作った記事を投稿したので気になる方は参考にしてください。

src/useTimeLeft.ts
import van from 'vanjs-core'

export const useTimeLeft = (initialNumber: number) => {
  const intervalId = van.state(0)
  // 残り時間
  const timeLeft = van.state(initialNumber)
  // アクティブかどうか
  const isActiveInterval = van.state(false)

  // 残り時間が0になったら、setIntervalを止める
  van.derive(() => {
    if (timeLeft.val === 0) {
      clearInterval(intervalId.val)
      isActiveInterval.val = false
    }
  })

  // スタート
  const start = () => {
    isActiveInterval.val = true

    // 1秒毎に残り時間を減らす
    intervalId.val = setInterval(() => {
      timeLeft.val--
    }, 1000)
  }

  // リセット
  const reset = () => {
    timeLeft.val = initialNumber
    isActiveInterval.val = false
  }

  return [
    timeLeft,
    isActiveInterval,
    {
      start,
      reset,
    },
  ] as const
}

まとめ

VanJSでクリックカウンターのアプリを作ってみました。カスタムフックを作ることで、メインの処理がスッキリしてコードの可読性が上がるのでおすすめです。

最後に

GoQSystemでは一緒に働いてくれる仲間を募集中です!

ご興味がある方は以下リンクよりご確認ください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?