Skip to content

Commit

Permalink
refactor: use requestAnimationFrame instead of setInterval
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisburnell committed Apr 22, 2024
1 parent fa700f3 commit 49eb5f2
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 20 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@chrisburnell/relative-time",
"version": "0.0.2",
"version": "0.0.3",
"description": "A Web Component to display a relative time.",
"author": "Chris Burnell <me@chrisburnell.com>",
"contributors": [
Expand Down
43 changes: 24 additions & 19 deletions relative-time.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,6 @@ class RelativeTime extends HTMLElement {
return
}

this.interval

if (!this.initialized) {
this.init()
}
Expand All @@ -61,21 +59,23 @@ class RelativeTime extends HTMLElement {
init() {
this.initialized = true

this.update = this.hasAttribute("update") ? Number(this.getAttribute("update")) : 600 // 600 * 1000 = 10 minutes
this.enableUpdates = this.getAttribute("update") !== "false"
this.division = this.getAttribute("division")
this.maxDivision = this.getAttribute("max-division")
this.update = this.hasAttribute("update") ? Number(this.getAttribute("update")) : 600 // 600 * 1000 = 10 minutes
this.lastUpdate = 0
this.enableUpdates = this.getAttribute("update") !== "false"
this.updateLoop

this.setString()

if (this.enableUpdates) {
this.beginInterval()
this.beginUpdateLoop()
window.addEventListener("blur", () => {
this.windowBlurHandler()
})
window.addEventListener("focus", () => {
this.windowFocusHandler()
})
window.addEventListener("blur", () => {
this.stopInterval()
})
}
}

Expand Down Expand Up @@ -105,24 +105,29 @@ class RelativeTime extends HTMLElement {
})
}

beginInterval() {
this.interval = setInterval(
() => {
beginUpdateLoop() {
const updateLoop = (currentTime) => {
this.updateLoop = requestAnimationFrame(updateLoop)
if (currentTime - this.lastUpdate >= this.update * 1000) {
this.setString()
this.beginInterval()
},
this.update * 1000
)
this.lastUpdate = currentTime
}
}
this.updateLoop = requestAnimationFrame(updateLoop)
}

stopUpdateLoop() {
this.lastUpdate = 0
cancelAnimationFrame(this.updateLoop)
}

stopInterval() {
clearInterval(this.interval)
windowBlurHandler() {
this.stopUpdateLoop()
}

windowFocusHandler() {
this.stopInterval()
this.setString()
this.beginInterval()
this.beginUpdateLoop()
}
}

Expand Down

0 comments on commit 49eb5f2

Please sign in to comment.