Timer
Hologram's timer class lets you run code at specific times.
everySecond(widget, cb)
Runs the specified callback every second.
let timerId = Hologram.timer.everySecond(this, () => {
// This will be called every second
console.log('Hello!')
})
// Stop the timer by running
Hologram.removeListener(timerId)
everyMinute(widget, cb)
Runs the specified callback once per minute when the minute changes. This should be used to update clocks and other things that need to update exactly when the minute increments.
let timerId = Hologram.timer.everyMinute(this, () => {
// This will be called every minute
console.log('Hello!')
})
// Stop the timer by running
Hologram.removeListener(timerId)
everyHour(widget, cb)
Runs the specified callback once per hour when the hour changes.
let timerId = Hologram.timer.everyHour(this, () => {
// This will be called every hour
console.log('Hello!')
})
// Stop the timer by running
Hologram.removeListener(timerId)
repeatOnceADayOn(widget, time, cb)
Calls the specified callback once per day at the specified time.
The time is specified as a string hours:minuets
. For example to call a timer at 12:30 you would use 12:30
. Hours are specified in 24 hour format.
Note that its not guaranteed that this timer will be called, because the widget may not exist at the specific time its triggered. For that reason, it's recommended that you include code that verifies that it was called when the widget is mounted.
For example, if your widget uses the below function to change a quote every day, make sure to check whether the quote needs to be changed when your widget is mounted. Don't rely solely on the timer to change it every day.
// Change the quote at the beginning of every day
Hologram.timer.repeatOnceADayOn(this, '0:0', () => {
this.refreshQuote()
})
// Do something at noon
let timerId = Hologram.timer.repeatOnceADayOn(this, '12:0', () => {
console.log('Its noon!')
})
// Stop the timer by running
Hologram.removeListener(timerId)
Using setInterval()
If you use setInterval()
because one of the above native functions doesn't provide the exact timing you need, it's very important that you store the interval Id for that timer in your code and explicitly destroy it when the widget is removed. If you don't don't do that, the timer will continue to run even after the widget has been removed.
Here is an example of how you do that using the Vue.js beforeDestroy()
method:
export default {
extends: HologramWidget,
data() {
return {
intervalId: false
}
},
mounted() {
this.intervalId = setInterval(() => {
this.someFunction()
}, 5000)
},
methods: {
someFunction() {
// Do something
}
},
beforeDestroy() {
clearInterval(this.intervalId)
},
template: /*html*/ `
<div class="widget-container">
<p>Hello World!</p>
</div>
`
}