packages/lit-dev-content/site/tutorials/content/word-viewer/04.md
By the end of this step, the shown word will automatically change every second.
This can be achieved by using
setInterval, a
browser function which repeatedly calls a function with a fixed delay between
each call.
Define a method tickToNextWord bound to the component that will increment
this.idx.
{% switchable-sample %}
// word-viewer.ts
render() {
...
}
tickToNextWord = () => { this.idx += 1; };
// word-viewer.js
render() {
...
}
tickToNextWord = () => { this.idx += 1; };
{% endswitchable-sample %}
Calling this method increments our reactive internal state idx which will
schedule an update.
{% aside "info" "no-header" %}
Since you'll use this method with setInterval, an arrow function can be used
such that this refers to the component. See the "this"
problem
for more info.
{% endaside %}
To setup the interval and clean up the interval, use the standard custom
element lifecycle
callbacks
connectedCallback, and disconnectedCallback.
connectedCallback is invoked when the component is added to the DOM, and
disconnectedCallback is invoked when the component is removed from the DOM.
{% switchable-sample %}
// word-viewer.ts
private intervalTimer?: number;
connectedCallback() {
super.connectedCallback();
this.intervalTimer = setInterval(this.tickToNextWord, 1000);
}
disconnectedCallback() {
super.disconnectedCallback();
clearInterval(this.intervalTimer);
this.intervalTimer = undefined;
}
// word-viewer.js
intervalTimer;
connectedCallback() {
super.connectedCallback();
this.intervalTimer = setInterval(this.tickToNextWord, 1000);
}
disconnectedCallback() {
super.disconnectedCallback();
clearInterval(this.intervalTimer);
this.intervalTimer = undefined;
}
{% endswitchable-sample %}
When the word-viewer is attached to the DOM, connectedCallback is invoked
and setInterval repeatedly calls this.tickToNextWord every 1000ms, or every
second.
The interval ID is stored on this.intervalTimer which does not need to be
reactive.
When word-viewer is removed from the DOM, disconnectedCallback is invoked
cleaning up the interval, and this.tickToNextWord is no longer called.
The preview should be cycling over individual words.
{% aside "info" "no-header" %}
Lit leverages standard custom element lifecycle callbacks.
If you customize any of the standard custom element lifecycle methods, make sure
to call the super implementation so the standard Lit functionality is
preserved. See lifecycle
docs for more info.
{% endaside %}