Refresh and toggle dataview/source

That’s also solvable :slight_smile:

I rewrote it to handle that, which actually makes the script better overall, so thank you for the suggestion.

Instead of checking the visibility of an element, we add an Observer on the Dataview container, which let’s us know when it goes in and out of view.

If it’s out of view we cancel the interval, and when it comes back into view we start a new interval.

To make it even easier to re-use the code on multiple pages, I turned it into a dv.view().

Put this with your Dataview scripts, called refresh.js:

/*
Call this file refresh.js and store it with your Dataview scripts.

Here's an example of using it to create a clock that updates each second:

dv.view('refresh', {
  contents: () => { 
    dv.paragraph(moment().format('HH:mm:ss'))
  },
  delay: 1000
})

*/
const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    clearInterval(entry.target.interval)
    entry.target.innerHTML = ''
    if (entry.isIntersecting) {
      // Show the user's contents
      input.contents()
      // Set up the interval
      entry.target.interval = setInterval(() => {
        entry.target.innerHTML = ''
        input.contents()
      }, input?.delay || 60000)
    }
  })
})
observer.observe(dv.container)

And then call it from any page like this:

```dataviewjs
dv.view('refresh', {
  contents: () => { 
    dv.header(5, 'This time will keep updating while the note is open:')
    dv.paragraph(moment().format('HH:mm:ss'))
    console.log(moment().format('HH:mm:ss'))
  },
  delay: 1000
})
```

You can see from the console that it will immediately cancel and resume as you change between different notes or the Source and Reading etc views.

You can even call another dv.view(...) from within the refresh block, which makes it pretty unlimited what you can have automatically updating:

```dataviewjs
dv.view('refresh', {
  contents: () => dv.view('some-fancy-view')
})
```
3 Likes