Reputation: 341
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)
Upvotes: 1
Views: 761
Reputation: 1074445
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;
}
Upvotes: 3
Reputation: 136114
Your code already does exactly what you describe. A small change is required to make bar
accessible outside of the function where it is initialized, but if you wait 6 seconds you'll see the result you expected in the example below.
var foo = 0;
var bar;
setInterval(function(){foo++}, 1000);
setTimeout(function(){bar = foo}, 4000) //bar = 4;
setTimeout(function(){
console.log(foo,bar)
}, 6000)
Upvotes: 3