I have a problem with my Javascript code and don't know why it doesn't run.
This is my timer:
var time = 0;
startTimer();
function startTimer(){
setInterval(function(){
time=time+1;
},10);
}
This code here works (I run timeoutTester() while clicking on a button, then it alerts and shows me the time difference):
function timeoutTester(){
var snap_time1 = time;
setTimeout(function(){
var snap_time2 = time;
var diff = snap_time2-snap_time1;
alert(diff); //works: ~100 everytime...
},1000);
}
But this code here doesn't work (I run testTimer() by clicking on a button):
function timeoutTester(){
var snap_time1 = time;
var result;
setTimeout(function(){
var snap_time2 = time;
result = snap_time2-snap_time1;
},1000);
alert(result); //doesn't work! It always shows me: "undefined"
return result;
}
function testTimer(){
var counter = 0;
setInterval(function(){
counter = counter + 1;
alert(counter); //works: 1,2,3,....
var result = timeoutTester();
alert(result); //doesn't work! It always shows me: "undefined"
}, 3000);
}
Do you know where the problem might be? (No error while debugging in browser!)
UPDATE:
I learned that alert(result); is executed immediately, while result has no value yet.
But since I'm calling timeoutTester() from the outside, I still need a return value from this function!
Any ideas?