I need to access this
from my setInterval
handler
prefs: null, startup : function() { // init prefs ... this.retrieve_rate(); this.intervalID = setInterval(this.retrieve_rate, this.INTERVAL); }, retrieve_rate : function() { var ajax = null; ajax = new XMLHttpRequest(); ajax.open('GET', 'http://xyz.com', true); ajax.onload = function() { // access prefs here } }
How can I access this.prefs in ajax.onload
?
setInterval() The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval() .
Nested setTimeout calls are a more flexible alternative to setInterval , allowing us to set the time between executions more precisely. Zero delay scheduling with setTimeout(func, 0) (the same as setTimeout(func) ) is used to schedule the call “as soon as possible, but after the current script is complete”.
In order to understand why setInterval is evil we need to keep in mind a fact that javascript is essentially single threaded, meaning it will not perform more than one operation at a time.
Good question, but in JS you can't. To have multiple functions in the same program execute at the same time you need multi-threading and some deep timing and thread handling skills. JS is single threaded.
this.intervalID = setInterval(this.retrieve_rate.bind(this), this.INTERVAL);
The setInterval line should look like this:-
this.intervalID = setInterval( (function(self) { //Self-executing func which takes 'this' as self return function() { //Return a function in the context of 'self' self.retrieve_rate(); //Thing you wanted to run as non-window 'this' } })(this), this.INTERVAL //normal interval, 'this' scope not impacted here. );
Edit: The same principle applies to the " onload
". In this case its common for the "outer" code to do little, it just sets up the request an then sends it. In this case the extra overhead an additinal function as in the above code is unnecessary. Your retrieve_rate should look more like this:-
retrieve_rate : function() { var self = this; var ajax = new XMLHttpRequest(); ajax.open('GET', 'http://xyz.com', true); ajax.onreadystatechanged= function() { if (ajax.readyState == 4 && ajax.status == 200) { // prefs available as self.prefs } } ajax.send(null); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With