Skip to content

Instantly share code, notes, and snippets.

@shystruk
Last active November 23, 2017 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shystruk/df6206e69b4ed775e325db7c96bce23b to your computer and use it in GitHub Desktop.
Save shystruk/df6206e69b4ed775e325db7c96bce23b to your computer and use it in GitHub Desktop.
Stop making HTTP requests if user has a nap
(function IIFE() {
let startDate = new Date()
// make HTTP request each 5 sec
let newUsers_Interval = new Interval(getAmoutNewUsers, 5000)
// checking each 15 min if user iteracts with page
let userHasNap_Interval = new Interval(clearIntervalsIfUserHasANap, 900000)
newUsers_Interval.start()
userHasNap_Interval.start()
$('body').click(() => {
startDate = new Date()
newUsers_Interval.start()
userHasNap_Interval.start()
})
function Interval(fn, interval) {
let timer
this.start = () => {
if (!timer) {
timer = setInterval(() => { fn() }, interval)
}
}
this.stop = () => {
clearInterval(timer)
timer = void 0
}
}
function clearIntervalsIfUserHasANap() {
let diffMinutes = Math.round((((new Date() - startDate) % 86400000) % 3600000) / 60000)
if (diffMinutes >= 15) {
newUsers_Interval.stop()
userHasNap_Interval.stop()
}
}
}())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment