userData not working on Script.setInterval


#1

Hi!
I’m writing a script to put entities back into place if they have been moved after a certain period of time.

I set 2 params in the userData such as interval and position. I am able to retrieve the params just fine. When I try to use them in Script.setInterval they do not work. setInterval seems to ignore the interval paramater.

Basically, I want to use a dynamic interval for setInterval method set by the userData.

Any ideas why or how to get around it? Here’s my code:

(function () {

//vars
var _entityID;
var newProperties = {};
var properties;

//userData
var interval = null;
var posX = null;
var posY = null;
var posZ = null;

//preload
this.preload = function (entityID) {
    _entityID = entityID;

    properties = Entities.getEntityProperties(_entityID, ["userData"]);

    //print("posX " + JSON.parse(properties.userData).posX);
    //print("posY " + JSON.parse(properties.userData).posY);
    //print("posZ " + JSON.parse(properties.userData).posZ);

    posX = JSON.parse(properties.userData).posX;
    posY = JSON.parse(properties.userData).posY;
    posZ = JSON.parse(properties.userData).posZ;

    interval = JSON.parse(properties.userData).interval;
    print("interval " + interval);

}

print("interval " + interval);

//interval
Script.setInterval(function () {

    reposition();

}, interval) // <------THIS DOES NOT WORK - the INTERVAL SET IN USERDATA is NOT READ

function reposition() {

    var originalPos = { x: posX, y: posY, z: posZ };

    var newProperties = {
        position: originalPos
    }
    Entities.editEntity(_entityID, newProperties);
}

});


#2

I don’t see where ‘preload’ function is executed


#3

Besides that if you want to have only one timer make sure to clear interval before each execution:

https://www.w3schools.com/jsref/met_win_setinterval.asp


#4

I found the solution. The preload takes longer to fire than the setInterval. So I embedded the setInterval in a setTimout and voila!