AzDeveloper AzDeveloper - 11 months ago 90
Javascript Question

Define a unchangeable variable

I have this code here:

var foo = 0;
setInterval(function(){foo++}, 1000);


This will increase
foo
by 1 every second. Is there any way to define a
bar
variable which will be the
foo
variable at that time and not changing?
It sounds confusing, so here:
For example:

var foo = 0;
setInterval(function(){foo++}, 1000);
setTimeout(function(){var bar = foo}, 4000) //bar = 4;


Is there anyway to keep
bar
at 4 and not increasing with
foo
? Thanks a lot!

(Sorry for bad English)

Answer Source

If you mean you want bar to be available in the same scope as foo, just move its declaration:

var foo = 0;
var bar;
setInterval(function() {
    foo++;
}, 1000);
setTimeout(function() {
    bar = foo;
}, 4000);

Once it gets that value assigned by the timer, it won't change again (unless you change it somewhere).

Live Example:

var foo = 0;
var bar;
setInterval(function() {
    foo++;
}, 1000);
setTimeout(function() {
    bar = foo;
}, 4000);
var stop = Date.now() + 10000;
var timer = setInterval(function() {
    console.log("foo = " + foo + ", bar = " + bar);
    if (Date.now() > stop) {
        clearInterval(timer);
    }
}, 1000);
.as-console-wrapper {
  max-height: 100% !important;
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download