Last active
August 15, 2022 17:25
-
-
Save xRoulanDx/e70e41d30ba8251e9fa8dad7ad979b8c to your computer and use it in GitHub Desktop.
Bookmarklet для отображения таймера в верхней части страницы
This file contains hidden or 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
javascript: (function() { | |
let interval; | |
let containerElt; | |
let minElt; | |
let secElt; | |
const template = | |
'<div id="aalexeev-timer" style="background: #434343; padding: 10px; text-align: center; font-size: 40px; font-family: monospace; color: #fff;"><span data-minutes></span>:<span data-seconds></span></div>'; | |
const DEFAULT_MINUTES = 10; | |
starter(); | |
function starter() { | |
var minutes = prompt('На сколько минут?', DEFAULT_MINUTES); | |
if (minutes) { | |
countdown(minutes); | |
} | |
} | |
function countdown(minutes) { | |
if (document.getElementById('aalexeev-timer')) { | |
return; | |
} | |
const container = document.createElement('div'); | |
container.innerHTML = template; | |
containerElt = container.firstChild; | |
document.body.insertBefore(containerElt, document.body.firstChild); | |
minElt = containerElt.querySelector('[data-minutes]'); | |
secElt = containerElt.querySelector('[data-seconds]'); | |
endDate = new Date(new Date().getTime() + minutes * 60 * 1000); | |
if (isNaN(endDate) || !minElt || !secElt) { | |
return; | |
} | |
calculate(endDate); | |
interval = setInterval(() => calculate(endDate), 500); | |
} | |
function calculate(endDateTime) { | |
let startDate = new Date(); | |
startDate = startDate.getTime(); | |
let timeRemaining = endDateTime - startDate; | |
if (timeRemaining >= 0) { | |
renderRemaining(timeRemaining); | |
} else { | |
clearInterval(interval); | |
containerElt.style.color = '#f44336'; | |
} | |
} | |
function renderRemaining(timeRemainingMS) { | |
const timeRemainingSec = parseInt(timeRemainingMS / 1000, 10); | |
const seconds = parseInt(timeRemainingSec % 60).toString(); | |
let minutes = parseInt(timeRemainingSec / 60, 10).toString(); | |
if (minutes.length < 2) { | |
minutes = '0' + minutes; | |
} | |
minElt.innerHTML = minutes; | |
secElt.innerHTML = ('0' + seconds).slice(-2); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment