JSの勉強でタイマーカウントライブラリを作成してみた!
概要
今まで何となくで書いていたJS。最近になってようやくモチベーションも少し上がってきたので新しく何かやってみようと思いました。
そこで、初めてライブラリを作成してみようと発起。
とりあえずは簡単なライブラリで挑戦ということで、サンプルとかでありそうなタイマーカウントのライブラリを作成してみました!
使い方
今回のはjqueryなしでもいけます。なので基本的にはどの環境でもいけるのではないかと思われます。
HTML
HTML側ではjsの読み込みと、カウンターの表示用のタグしか記述しておりません。
見た目はまったく装飾していないので、ご自身のサイトで使用する場合はCSSでお好きなように装飾してください。
<!DOCTYPE html>
<html>
<head>
<title>setTimerCount.js</title>
<script src="./assets/js/setTimerCount.js"></script>
<script src="./assets/js/index.js"></script>
</head>
<body>
<div class="contents">
<div class="inner">
<div>
<p id="timer_count_set1"></p>
</div>
</div>
</div>
</body>
</html>
JS
setTimerCount.js
これが本体側のJSファイルになります。
ここは基本的にいじる必要はありません。
let TimerSetCounter = (function () { });
TimerSetCounter.prototype = {
getDefaultOptions: function (options) {
let defaultOptions = {};
if (options) {
defaultOptions = options;
} else {
defaultOptions = {
max_count: 100,
count_separate: 1000,
finish_method: function () {
},
};
}
return defaultOptions;
},
countTimerSet: function (targetEle, options) {
this.countTimer(targetEle, options);
},
countTimer: function (targetEle, options) {
const option = this.getDefaultOptions(options);
const target = document.getElementById(targetEle);
let max_count = option.max_count;
let timer_id = 0;
const countDown = () => {
timer_id = setTimeout(countDown, option.count_separate);
if (max_count >= 1) {
max_count--;
} else {
this.countFinished(option);
clearTimeout(timer_id);
}
target.textContent = max_count;
return max_count;
}
current_timer = countDown();
return current_timer;
},
countFinished: function (options) {
const option = this.getDefaultOptions(options);
if (option.finish_method) {
option.finish_method();
}
}
};
index.js
これが呼び出し側のJSになります。
オプションをほんの少しだけですが使用できるようにしてありますので、ご利用くださいませ。
window.onload = function () {
const timerSetCounter1 = new TimerSetCounter();
const options = {
max_count: 10,
count_separate: 1000,
finish_method: function () {
console.log('終了');
},
};
timerSetCounter1.countTimerSet('timer_count_set1', options);
};
finish_method: function () {
console.log('終了');
},
この部分でカウンターが0になったら何か任意で処理ができるようにしてあります。
「finish_method」の中身は今はconsole.logしか書いてありませんが、何かしたい処理を書いてください。
例)Domの操作とか
最後に
コードが汚くて申し訳ないです。。
一応動くと思いますので良かったら使ってやってください!