I have this code here:
var foo = 0;
setInterval(function(){foo++}, 1000);
foo
bar
foo
var foo = 0;
setInterval(function(){foo++}, 1000);
setTimeout(function(){var bar = foo}, 4000) //bar = 4;
bar
foo
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;
}