[SOLVED] How to make a code run in every 10 frame not every frame

I am trying to create a code to animate the second hand of a mechanical clock, the movement should not be continuous but doing “jumps” I am using this script but I don’t know how to modify it so that it only runs every 10 frames and make the movement of the second hand be like that of a winding clock, with small intervals in the movement

var Rotate = pc.createScript('segundero');

Rotate.attributes.add('speed', { type: 'number', default: 10 });

// initialize code called once per entity
Rotate.prototype.initialize = function() {
    this.local = false; // choose local rotation or world rotation
};

// update code called every frame
Rotate.prototype.update = function(dt) {
    if (this.local) {
        this.entity.rotateLocal(0, this.speed * dt, 0);
    } else {
        this.entity.rotate(0, this.speed * dt, 0);
    }
};


// swap method called for script hot-reloading
// inherit your script state here
Rotate.prototype.swap = function(old) {
    this.local = old.local;
};

A more robust approach would be to set the rotation of the second hand based on the number of seconds that has elapsed.

eg (not actual code):

Rotate.prototype.initialize = function() {
    this.secondsElapsed = 0;
    this.local = false; // choose local rotation or world rotation
};

// update code called every frame
Rotate.prototype.update = function(dt) {
    this.secondsElapsed += dt;
    var yRotation = Math.floor(this.secondsElapsed) * (360 / 60);
    if (this.local) {
        this.entity.setLocalEulerAngles(0, yRotation, 0);
    } else {
        this.entity.setEulerAngles(0, yRotation, 0);
    }
};

If that looks good! It is more solid to focus on that way, thanks

Unsure if this would work, but I think you can set a timeout here.

var Rotate = pc.createScript('segundero');

Rotate.attributes.add('speed', { type: 'number', default: 10 });

// initialize code called once per entity
Rotate.prototype.initialize = function() {
    this.local = false; // choose local rotation or world rotation
};

// update code called every frame
Rotate.prototype.update = function(dt) {
setTimeout(function () {
    if (this.local) {
        this.entity.rotateLocal(0, this.speed * dt, 0);
    } else {
        this.entity.rotate(0, this.speed * dt, 0);
    }
}.bind(this), 10);
};


// swap method called for script hot-reloading
// inherit your script state here
Rotate.prototype.swap = function(old) {
    this.local = old.local;
};

Many Thanks!!!

The problem with setTimeout is that the timeout will continue to elapse even if the tab is not active (user has switched to another tab). PlayCanvas’ update functions, on the other hand, will pause, essentially freezing your game/app. So you might get undesired behavior if you use setTimeout rather than use the method @yaustar recommended.

2 Likes