Variable Handling with Set Interval Loop
An exploration of how simple variables and object variables are handled in JavaScript. Related: http://stackoverflow.com/q/15099929/918414
by Brian Layman
HTML
You will see that label1 is passed by value, but not at the time of definition. Its value is whatever it is at the time of calling and in this example remains the same after 2 is assigned to it.<br><br>
Label2 is global scope and there for can be changed everywhere, but is NOT passed in.<br><br>
LabelObj is passed in, but is an object. <br><br>And through this we see that basically everything is passed by value, but for objects the value is the memory address storing the variable. <br> So you can cheat and get pass by reference using through use of an object.<br>
<div id="result"></div>
<script>
/* by: thinkingstiff.com
license: http://creativecommons.org/licenses/by-nc-sa/3.0/us/ */
var headerCaption = 'set-interval and clear-interval inside for loop',
headerUri = 'http://stackoverflow.com/q/15099929/918414';
document.body.insertAdjacentHTML(
'afterBegin',
'<a...
JavaScript
function checkTime( label, labelObj ) {
document.getElementById( 'result' ).insertAdjacentHTML(
'beforeEnd',
label + ": " + label2 + ' | ' + labelObj.a + '<br />'
);
}
function incVars( labelX, labelObjX ) {
// Since the object was passed by value, the property's value is the memory address of variable
// So changing it changes the value of that property globally.
labelObjX.a++;
// These variables have different names to prove that scope has nothing to do with this
labelX = 'z' + labelX; // ignored because passed by value
// Label2 is passed by scope
label2++
}
function start() {
// let defines these variables to the scope of this function.
// Try also with let removed.
label1 = 1;
labelObj = {a:1};
setInterval( function(){ checkTime(label1, labelObj) }, 1000 );
// This new assignment happens almost immediately. So the value of 1 is never seen in the output
label1 = 2;
labelObj.a = 2;
label2++;
setInterval( function(){ checkTime(label1, labelObj) }, 1000 );
// If passed by reference, this would increment the label.
setInterval( function(){ incVars(label1, labelObj) }, 2000 );
}
label2 = 900;
start();