Last active
April 4, 2020 10:14
-
-
Save cocoabox/e3a37ff2aaebb888625c18832ce6405a to your computer and use it in GitHub Desktop.
close timer bookmarklet
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
void(function(){ | |
function sec2time_str(sec) { | |
let h=''; | |
let m=''; | |
let s=''; | |
if (sec > 3600) { | |
h = Math.floor(sec / 3600); | |
sec -= 3600*h; | |
h = `${h} hrs`; | |
} | |
if (sec > 60) { | |
m = Math.floor(sec / 60); | |
sec -= 60*m; | |
m = `${m} min`; | |
} | |
if (sec) { | |
s = `${sec} sec`; | |
} | |
return [h, m, s].join(' ').trim(); | |
} | |
function bye() { | |
if (window.__close_timer.timer) { | |
window.clearInterval(window.__close_timer.timer); | |
} | |
window.__close_timer.timer = ''; | |
window.__close_timer.active = false; | |
window.__close_timer.sec = 0; | |
window.__close_timer.title = ''; | |
} | |
function onInterval() { | |
window.__close_timer.sec -= 1; | |
if ( window.__close_timer.sec <= 0 ) { | |
bye(); | |
window.close(); | |
return; | |
} | |
let time_str = sec2time_str( window.__close_timer.sec ); | |
document.title = `⏲ [${time_str}] - ${window.__close_timer.title}`; | |
debugger; | |
}; | |
// main | |
if (typeof window.__close_timer === 'undefined') { | |
window.__close_timer = {}; | |
} | |
if (window.__close_timer.active) { | |
let time = sec2time_str(window.__close_timer.sec); | |
if (window.confirm(`⏲ :${time}\n🚫⏲?`)) { | |
document.title = window.__close_timer.title; | |
bye(); | |
return; | |
} | |
else { | |
return; | |
} | |
} | |
// find a <video> get remaining time | |
let suggestedTime = '10m'; | |
let v = document.querySelector('video'); | |
if (v) { | |
let video_time = Math.floor(v.duration - v.currentTime) + 5; | |
suggestedTime = sec2time_str(video_time); | |
} | |
// start new timer | |
let user_time_str = window.prompt('⏲💤 →❌', suggestedTime).trim(); | |
if (! user_time_str) { | |
return; | |
} | |
const re = /^(([0-9\.]+)\s*(hours|hour|hrs|hr|h))?\s*(([0-9\.]+)\s*(minute|minute|mins|min|m))?\s*(([0-9\.]+)\s*(seconds|second|secs|sec|s))?$/; | |
let mat = user_time_str.toLowerCase().match(re); | |
let sec = 0; | |
if (mat[2]) { | |
sec += parseFloat(mat[2]) * 3600; | |
} | |
if (mat[5]) { | |
sec += parseFloat(mat[5]) * 60; | |
} | |
if (mat[8]) { | |
sec += parseInt(mat[8]); | |
} | |
sec = Math.floor(sec); | |
window.__close_timer.title = document.title; | |
window.__close_timer.sec = sec; | |
window.__close_timer.timer = window.setInterval(onInterval, 1000); | |
window.__close_timer.active = true; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment