Reputation: 190
I want to update a variable on a given time interval with a function. Here's my code:
var heroVel1 = game.currentHero.GetLinearVelocity().x;
var heroVel2 = '';
setInterval(function() {
var heroVel2 = heroVel1;
}, 2000);
console.log(heroVel2);
I've tried many different solutions with setInterval() and Timeout(), but don't know why it doesn't work. I want to console.log the changed variable.
I'm a newbie and been stuck with this the whole day. All help/feedback is highly appriciated!!
Upvotes: 0
Views: 3903
Reputation: 1184
you are defining a new variable inside the setInterval instead of reusing heroVel2..
try:
setInterval(function() {
heroVel2 = heroVel1;
console.log(heroVel2);
}, 2000);
This should update the heroVel2 in the outer scope aswell as write to the console every 2 seconds.
UPDATE:
Ok so based on your comments it has become clear that this is all done in a continous loop, which is why you are getting spammed with console.logs.
What you would do is NOT use setInterval and instead do time comparison. The problem is that when setInterval is called the function inside it is immediately called. So when you execute a setInterval every 10ms, you'll get a console.log every 10ms.
outside of you gameloop define a:
timeLastUpdated = new Date().getTime();
and inside the loop, you would check to see if the currentTime - timeLastUpdated >= 2000 if it is, then you will set timeLastUpdate to currentTimeMillis. This way you will get an action to happen every 2000ish miliseconds.
timeLastUpdated = new Date().getTime(); // Gets the time in millis
function gameLoop() {
var currentTimeMillis = new Date().getTime(); // For each trip through this loop, set currentTimeMillis to the currentTime.
if( currentTimeMillis - timeLastUpdated >= 2000) { // has it been more than 2000milis since last?
heroVel2 = heroVel1;
console.log(heroVel2);
timeLastUpdated = currentTimeMillis;
}
Upvotes: 4
Reputation: 1
The interval you have provided is updating the value of heroVel2
every 2 seconds, but nothing else. If you want the new value to be logged, you must also include the log within the interval.
setInterval(function() {
heroVel2 = heroVel1;
console.log(heroVel2);
}, 2000);
Of course, the value that you are updating it to here doesn't change, since heroVel1
has not changed. To ensure you get the updated value, you would have to refetch it from game.currentHero.GetLinearVelocity().x
like so:
setInterval(function() {
heroVel2 = game.currentHero.GetLinearVelocity().x;
console.log(heroVel2);
}, 2000);
And, depending on the needs of your script, this may make the variables useless, as you could simply pass the current velocity as an argument to console.log
directly.
Upvotes: 0