1

So all I want is to change this object using a while loop in a method, which I call from a button event. My only problem is that the cameraPosition data does not change while I increment it in the loop, it only changes value when the function is over.

Any help would be much appreciated!

data() {
  return {
    cameraPosition: { x: 0, y: 0, z: -60 }
  methods: {
    sleep(milliseconds) {
     const date = Date.now();
     let currentDate = null;
     do {
       currentDate = Date.now();
     } while (currentDate - date < milliseconds);
    },

   animation(destinationPos) {
     while (this.cameraPosition.z < destinationPos.z) {
       this.cameraPosition.z = this.cameraPosition.z + 1;
       sleep(200)
   }
  },
 }

1 Answers1

1

You sleep method is blocking.

Make the function asynchronous. use this instead :

   async animation(destinationPos) {
     while (this.cameraPosition.z < destinationPos.z) {
       this.cameraPosition.z = this.cameraPosition.z + 1;
       await new Promise(r => setTimeout(r, 2000));
   }

https://stackoverflow.com/a/39914235/5671919

Pierre Said
  • 3,660
  • 1
  • 16
  • 28