I'm trying to use the system clock to make a simple animation in Javascript. I want to cycle through an array so that [0],[1],[2]...
are called at 500ms
intervals. Using an example from a previous Stack Overflow answer I was experimenting with this code snippet:
function timer(time,update,complete) {
var start = new Date().getTime();
var interval = setInterval(function() {
var now = (time*1000)-(new Date().getTime()-start);
if( now <= 0) {
clearInterval(interval);
complete();
}
else update(Math.floor(now/1000));
},500); // the smaller this number, the more accurate the timer will be
}
The function is then called using the following approach:
timer(
5, // seconds
function(timeleft) { // called every step to update the visible countdown
console.log(3 - timeleft );
},
function() { // what to do after
console.log("Timer complete!");
}
);
This produces, 0,1,2,3,"Timer Complete"
. However, I can't figure out how this can be called at 500ms intervals. I've tried tweaking the numbers, but I realize that I don't fully understand how this function works. Is it possible to adjust this, or are there some hard coded browser functions that are being called here on the 1s interval?
I tried changing all of the values to the following:
function timer(time,update,complete) {
var start = new Date().getTime();
var interval = setInterval(function() {
var now = (time*500)-(new Date().getTime()-start);
if( now <= 0) {
clearInterval(interval);
complete();
}
else update(Math.floor(now/500));
},500); // the smaller this number, the more accurate the timer will be
}
timer(
5, // seconds
function(timeleft) { // called every step to update the visible countdown
console.log(5 - timeleft );
},
function() { // what to do after
console.log("Timer complete!");
}
);
This now produces:
2
3
4
5
Timer complete!
at what I think are 500ms intervals, but I'm not sure. Changing the value 5
in 5 - timeleft
also does strange things to the speed at which this runs.