Reputation: 1681
I am trying to set a variable initially only if it has not been set. For some reason the logic I'm using to determine whether the variable has been set seems to run even regardless of whether the variable has been set.
My code is
var l0 = -210;
function add(){
var lThis;
if (lThis == null){
lThis = l0;
console.log('set lThis to '+ lThis);
}
lThis ++;
}
var incrementInterval = setInterval(add, 33);
The console logs "set lThis to -210" every time the interval runs, so the "if (lThis == null)" seems to be doing nothing
Upvotes: 1
Views: 83
Reputation: 135247
For what it's worth I think your whole code snippet needs a dramatic rewrite
function add (x) {
console.log(x)
setTimeout(add, 33, x + 1)
}
let timeout = add(-210)
If you really want a global variable for some (probably bad) reason
let x = -210
function add () {
console.log(x)
x = x + 1
}
let timeout = setInterval(add, 33)
And another
function delay (ms) {
return new Promise(r => setTimeout(r, ms))
}
async function add (x) {
console.log(x)
await delay(33)
add(x + 1)
}
add(-210)
And... no just kidding. There are no more examples.
Upvotes: 0
Reputation: 49
lThis
is a local variable. This variable would be reset to 'null' every 33ms, when add()
gets called.
What about another global variable, like this:
var l0 = -210;
var lThis;
function add() {
if (lThis == null) {
lThis = l0;
.......
Upvotes: 1
Reputation: 21854
lThis
is a local variable in your example. So lThis
will be reinitialized to undefined
each time the function add()
is called, and you will never reach lThis++
. You probably want to move lThis
outside of add()
:
var lThis;
function add() {
if (!lThis) {
lThis = l0;
console.log('set lThis to '+ lThis);
}
lThis++;
}
Upvotes: 1
Reputation: 1233
With setInterval function add is executed every 33ms from the start, do the whole function scope is recreated, including lThis. I suppose what you want to achieve is to add 1 on every call to lThis within function. One of ways to achieve that is using closure in the following way:
var l0 = -210;
function thunkAdd(){
var lThis = l0;
console.log('set lThis to '+ lThis);
return function inc() {
console.log(lThis);
return lThis ++;
}
}
var incrementInterval = setInterval(thunkAdd(), 33);
Note, this is the old way of writing JavaScript, with new ES6 syntax it can be achieved in much more compact form:
const l0=-210;
function *add() {
let lThis = l0;
while (true) yield lThis++;
}
const lAdd = add()
const incrementInterval = setInterval(() => {console.log(lAdd.next())}, 33);
Upvotes: 1
Reputation: 885
Your variable lThis
is a local variable, it exists (and created each time) only in the scope of function add()
.
If you want to preserve a value of lThis
during the setInterval(...)
you should consider to move it to the global scope:
var lThis = null;
function add() {
if (lThis == null) {
lThis = -210
console.log('set lThis to '+ lThis);
}
lThis++;
}
Upvotes: 1