My variable of numbers updates every one second with mathrandom to some numbers like “14323121” I want to also every seccond save these to an array for say the latest 10 or so.
function EveryOneSec() {
var numbers = math.Random(); // I want to create an array from this...
setTimeOut(EveryOneSec, 1000);
};
To bind “numbers” to an array: (Referencing to var numbers above) I want to create an array like below for say the 10 last updates?
{"numbers":["2021030213","32454253"]} // For Reigel..
//doesnt have to be key value pairs. just need the value in legit json.
What is wrong with the your approach? Just setup your variables outside of the function that is repeated and then JSON encode it.
However, I think your task might be an excellent opportunity to use a custom event! You tagged your question jQuery, so you should check out its bind() method. Of course there are many tutorials on the topic.
As you can see, there’s a lot more code here. However, introducing a custom event gives you a lot of power, as now you have decoupled the the variable updating from the JSON creation. Furthermore, you can add additional listeners, perhaps to also log the updated array, and to insert additional steps between array update and JSON creation. For instance,
EveryOneSec()could trigger a different event,verifyArrayEvent, and only if the array validates does it triggerarrayUpdatedEvent.Update: From the comments to the question it looks like Ozaki isn’t clear that they can access a previously defined variable within their timer function. By defining a variable outside of a function and then referencing it inside of the function without using var, which would create a new, local variable, you are creating a closure where what you do to the variable inside of the function will be available outside of it. As you probably noticed, I used this technique in both my examples.
Hope that helps.