Jiří ProcházkaArticles

Jiří ProcházkaArticles

VueNuxt#frontend

setInterval on Nuxt server

3 quarters ago - 5 min read #nuxt

In javascript setInterval function is used to repeatedly call a function or execute a code snippet, with a fixed time delay between each call.

// this will write to developer console 'Hit!' every two seconds
setInterval(() => console.log('Hit!'), 2000);

You can also stop the execution

// this will write to developer console 'Hit!' every two seconds, but only 3x times
let counter = 0;
const interval = setInterval(() => {
  console.log('Hit!');
  if (counter === 2) {
    clearInterval(interval);
  }
  i++;
}, 2000);

Using it in Nuxt

When writing this page I'm using setInterval for rotating words in the page logo.

Using setInterval during SSR can lead to memory leaks or getting the node process stuck during nuxt generate. Since Nuxt version 3.10 it is even throwing an error.

Of course it doesn't mean you shouldn't be using setInterval at all. Either you can run it on the client side only, or you can use onNuxtReady composable [here].

onNuxtReady(() => {
  setInterval(() => {
    rotate(props.words);
  }, 2000);
});

Conclusion

That's it! When you need to use setInterval on client side of Nuxt application, wrap it to onNuxtReady.

Jiří Procházka Newsletter

Want to get new tips for Vue & Nuxt?