Set Javascript Variable Every N Sec. When It's Changed Also Create A Json Array Of Variable?
Solution 1:
What is wrong with the your approach? Just setup your variables outside of the function that is repeated and then JSON encode it.
var numbers = [];
var jsonString = "";
functionEveryOneSec() {
numbers.push(Math.random());
jsonString = JSON.stringify({'numbers': numbers});
setTimeout(EveryOneSec, 1000);
}
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.
var numbers = [];
var aPlaceholder = document.createElement("div");
aPlaceholder.bind("arrayUpdatedEvent", {'numbers': numbers}, arrayUpdatedHandler);
functionarrayUpdatedHandler(event) {
var jsonString = JSON.stringify(event.data);
// do something with your JSON
}
functionEveryOneSec() {
// add number to array
numbers.push(Math.random());
// trigger custom event
aPlaceholder.trigger("arrayUpdatedEvent");
}
// call every 1 second, store in var to be able to cancel it latervar myInterval = setInterval(EveryOneSec, 1000);
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 trigger arrayUpdatedEvent
.
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.
Post a Comment for "Set Javascript Variable Every N Sec. When It's Changed Also Create A Json Array Of Variable?"