I am developing a front-end application that loop through an array comprised of acceleration values and timestamps. These values will be used in animating a div (a moving vehicle).
To prevent parsing and loading the entire JSON file at once, I added a setTimeout
to loop through the strings every second. To make use of this incoming data, I then need to access these values in another function which will be fed to css keyframes as a dynamic values. The ultimate goal is to animate the div according to the incoming data.
I have an issue in accessing the value from the json string outside of the myLoop() function.
I have the following json string:
data=[
{
"time": 0,
"accX": 0.11,
"accZ": 0.11
},
{
"time": 86400,
"accX": 0.11,
"accZ": 0.11
},
{
"time": 172800,
"accX": 0.11,
"accZ": 0.11
},
{
"time": 259200,
"accX": 0.11,
"accZ": 0.11
},
{
"time": 345600,
"accX": 0.35,
"accZ": 0.11
}
]
Here is my function that loop through the json string every second:
var i = 0;
var data = JSON.parse(JSON.stringify(data));
let acceleration_x,acceleration_z,timestamp;
function myLoop() {
window.setTimeout(function() {
acceleration_x = data[i].accX;
acceleration_z = data[i].accZ;
timestamp = data[i].time;
i++;
if (i < data.length) {
myLoop();
}
console.log(acceleration_x, acceleration_z,timestamp)
}, 1000)
return {
acceleration_x,
acceleration_z,
timestamp
};
}
I need to access acceleration_x, acceleration_z and timestamp in this function:
function play(animation) {
myLoop(); // Here i need to access the acceleration and timer value and feed it to the keyframes
$('.track').resetKeyframe(function() {
switch (animation) {
case 'normal':
$('.track').playKeyframe({
name: 'carMove',
duration: "13s",
timingFunction: 'linear',
iterationCount: 'infinite',
direction: 'normal',
fillMode: 'forwards'
});
$('.car').playKeyframe({
name: 'shake',
duration: "3s",
timingFunction: 'linear',
iterationCount: 'infinite',
direction: 'normal',
fillMode: 'forwards'
});
break;
}
})
}
I am not sure where I am doing wrong. Any help would be appreciated.