Created
February 19, 2022 12:01
-
-
Save mahmutbayri/f4ef0ca7b581c65300628fe4be3213f4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Simple CountDown</title> | |
</head> | |
<body> | |
<span id="timer-container">00:00</span> | |
<script> | |
/** | |
* @param timerLength int | |
* @param timerContainer HTMLElement | |
* @param autoStart bool | |
* @param autoRestart bool | |
* @param onCompleteCallback function | |
* @returns {{start: startTimer}} | |
*/ | |
function simpleCountDownTimer(timerLength, timerContainer, autoStart, autoRestart, onCompleteCallback) { | |
const init = function () { | |
if(autoStart) { | |
startTimer(); | |
} | |
}; | |
const timerCompleted = function () { | |
onCompleteCallback(); | |
if(autoRestart) { | |
startTimer(); | |
} | |
}; | |
const tick = function (milliSecondsDiff) { | |
timerContainer.textContent = new Date(milliSecondsDiff).toISOString().substr(14, 5); | |
} | |
const startTimer = function () { | |
const startDate = new Date(); | |
const endDate = new Date(startDate.setSeconds(startDate.getSeconds() + timerLength)); | |
const timer = setInterval(function () { | |
const milliSecondsDiff = endDate.getTime() - Date.now(); | |
if (milliSecondsDiff <= 0) { | |
clearInterval(timer); | |
timerCompleted() | |
return; | |
} | |
tick(milliSecondsDiff); | |
}, 1000) | |
}; | |
init(); | |
return { | |
start: startTimer, | |
} | |
} | |
////////// USING | |
const timer = simpleCountDownTimer( | |
10, | |
document.querySelector('#timer-container'), | |
true, | |
false, | |
function () { | |
console.log('timer completed'); | |
// timer.start() | |
} | |
); | |
// const timer = simpleCountDownTimer( | |
// 10, | |
// document.querySelector('#timer-container'), | |
// false, | |
// false, | |
// function () { | |
// console.log('timer completed') | |
// } | |
// ); | |
// timer.start() | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment