JavaScript has two kind of timers, one provides a timeout (delayed execution of a piece of code) called window.setTimeout
(because setTimeout is a method of the window
object) and a timer that runs a piece of code after a certain interval called window.setInterval
.
Watch how both work
setTimeout(function(){
document.getElementById("showcase").innerHTML += "setTimeout fired only once after 3 seconds. <br />"}, 3000);
setInterval(function(){
document.getElementById("showcase").innerHTML += "setInterval fired every after 5 seconds. <br />"}, 5000);
//not part of the solution, just to demonstrate.
setInterval(function(){
document.getElementById("timer").textContent = 1 + parseInt(document.getElementById("timer").textContent);
}, 1000)
#showcase {
padding: 4px;
border: 1px solid grey;
background-color: #f3f3f3;
}
<span id="timer">0</span> seconds <br />
<div id="showcase"></div>
To let a timer run multiple times use setInterval.
On your case
setTimeout(function(){
var lat_in=5;
var long_in=5;
var alt_in=-5;
}, 3000);
When you replace setTimeout
to setInterval
it still won't work. As others commented, you are declaring the lat_in
etc. inside the scope
of the function. This means that the variables inside that function are only accessibele inside the function bound to the interval. The keyword is var
. It tells the parser to "bind" the variables to the scope of the function. Leave the var
and your timer function will overwrite the global variables declared outside the function. The sample below should be fine.
setInterval(function(){
lat_in=5;
long_in=5;
alt_in=-5;
}, 3000);
Also when you first declared the variables they are declared as an empty object.
var lat_in={};
var long_in={};
var alt_in={};
using {}
is the same as doing lat_in = new Object()
. However in your function you overwrite them with integers. Maybe this isn't meant to be. Check the documentation on your GPS coding to what input it needs.
While we are at it:
you can stop timers too with window.clearTimeout
and window.clearInterval
. Each referring to its own function of course.
To do this, you need to store the timer into a variable:
timer = window.SetInterval(function(){ ... }, 3000); //always in milliseconds.
clearInterval(timer); // this line will now clear the timer.
Also a smart person could remark: "I can let setTimeout
behave like an interval."
window.setTimeout(myTimerFunction, 3000);
function myTimerFunction(){
//do stuff here
window.setTimeout(myTimerFunction, 3000); //call itself again in three seconds.
}