Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
More Efficient Method for Dynamically Changing Text in JavaScript/Vue

I am working in Vue and I am dynamically changing text using setInterval() and a data() property.

I have a working method but I am wondering if there is a more efficient/way to optimize the method...or is it as optimized as it can be?

Optimize meaning: best for memory usage as well as is the code as simple as it can be?

 <h1>
    <span>{{ action }}</span> for everyone.
  </h1>
<script>
export default {
  name: "HeadLine",
  data() {
    return {
      action: "Build",
    };
  },
  methods: {
    changeTitle() {
     setInterval(() => {
        const actions = ["Build", "Create", "Design", "Code"];
        const currentActionIndex = actions.indexOf(this.action);
        //Send back to index of [0] === Build
        const nextActionIndex = (currentActionIndex + 1) % 4;
        let nextAction = actions[nextActionIndex];
        this.action = nextAction;
      }, 3000);
    },
  },
};
</script>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Rendering speaking, Vue is already doing the best job possible.

About your text rotating function, it can be improved a little bit, but it's a simple function, you won't gain much of memory usage.

// Stores the actions out of the component. It doesn't need to be reactive if it's static.
// You're avoiding having Vue's proxy above this array.
const actions = ["Build", "Create", "Design", "Code"];

export default {
  data () {
    return {
      // The only reactive data you need is the index of the word you want to show
      wordIndex: 0,
    }
  },
  computed: {
    // Let view update the text when the index changes. Computed properties use caching.
    action() {
      return actions[this.wordIndex]
    }
  },
  methods: {
    changeTitle() {
      setInterval(this.initRotation, 3000)
    },
    initRotation () {
      // Update the current word index
      this.wordIndex = (this.wordIndex + 1) % actions.length;
    }
  },
  beforeDestroy() {
    // Remove the interval runner when the component is destroyed!
    clearInterval(this.initRotation)
  }
}

As said, this won't change drastically the component performance. It's already too simple to feel a change.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!