[Vuejs]-Change setInterval interval from 100ms to 50ms

2👍

You could potentially write it using setTimeout instead of setInterval, dodging the problem of clearing the original timer:

data: {
  crashValue: 0,
},
mounted () {
  this.startTimer();
},
methods: {
  crashFunction () {
    this.crashValue += 0.0150; // Should this be 0.0150 or 0.0152?
    this.startTimer();
  },
  startTimer () {
    setTimeout(this.crashFunction, this.crashValue > 1 ? 50 : 100);
  }
}

2👍

You need to stop the old interval timer when you start the new one. So you need to save the timer in a variable.

You should check that you’re actually crossing the threshold, so you need to check that the old value of crashValue is less than 1 and the new value is at least 1. this.crashValue == 1 is never going to happen because 1 isn’t a multiple of 0.015 (and you should also avoid using == with floating point, because of roundoff errors).

data:{
    crashValue: 0,
    timer: null
  },
  mounted(){
    this.data.timer = setInterval(this.crashFunction,100);
  },
  methods:{
    crashFunction: function() {
      let oldcrashValue = this.crashValue;
      this.crashValue += 0.0150;
      if(oldCrashValue < 1 && this.crashValue >= 1){
        clearInterval(this.timer);
        this.timer = setInterval(this.crashFunction,50)
      }
    },
  }
👤Barmar

0👍

Existing interval cannot be changed, only cancelled. As other answers explain, another 50ms setInterval or setTimeout should be set instead of 100ms when the time comes.

If intervals are multiples, this can be done with single interval that is a common denominator:

crashFunction: function() {
  if (this.crashValue < 1 && this.i % 2)
    return; // skip every second time 

  this.i++; // not tied to exact crashValue
  this.crashValue += 0.0150;
},

Leave a comment