Reputation: 787
I'm trying to create function that increments numbers, so it looks like a digital clock kind of thing. The function takes two timestamps as param and increments between those. But since hh(hours) has a smaller range than mm(minutes), the hours always finishes first. I want the two to finish at the same time.
Here is my code.
var start = $('.clock').attr('data-from').split(":"); //eg. 10:23
var end = $('.clock').attr('data-to').split(":"); //eg 18:38
var clock = function (start, end, el) {
if($('.clock').length) {
var interval = setInterval(function() {
el.text(start);
if (start >= end) {
clearInterval(interval);
}
start++;
}, 50);
}
};
clock(start[0],end[0],$('.clock .h'));
clock(start[1],end[1],$('.clock .m'));
So, how can I make the interval to finish both animations at the same time?
Upvotes: 0
Views: 87
Reputation: 34168
My previous answer was not properly using a "time to animate" effectively and some values would post slower than others so I removed that one and simplified it down to this: fiddle:https://jsfiddle.net/MarkSchultheiss/67wyzk2m/2/
Markup
<div class="container" data-from="01:00" data-to="18:50">
<span class="h"></span>
<span>.</span>
<span class="m"></span>
</div>
New code:
var clockR = function(start, end, el, timerP) {
var currentCount = start;
el.text(currentCount);
var timer = timerP || 1;
var interval = setInterval(function() {
el.text(currentCount);
if (start >= end) {
clearInterval(interval);
}
currentCount++;
}, timer);
};
var start = $('.container').attr('data-from').split(":");
var end = $('.container').attr('data-to').split(":");
var animateLength = 30000; // ms to count for
var s0 = end[0] - start[0];
var s1 = end[1] - start[1];
var t0 = Math.abs(Math.trunc(animateLength / s0));
var t1 = Math.abs(Math.trunc(animateLength / s1));
clockR(start[0], end[0], $('.container .h'), t0);
clockR(start[1], end[1], $('.container .m'), t1);
Upvotes: 1
Reputation: 189
You need to use a number they can both (hours and minutes) divide.
So let's say you want to go from 10:20 to 12:30, the hour difference is 2 and the minutes difference is 10. Multiply them, you get 20.
Let's say you want your all animation to happen within 100 millisecond.
Divide your 100 by 20, you get 5. So 5 will be your interval.
Divide 100 by 2 (the number of hours) = 50, the hours will have to be updated when the rest of the total of the intervals divided by 50 = 0, so totalInterval % 50 === 0
.
Same for the minutes, 100/10 = 10, so when totalInterval % 10 === 0
, increment your minutes.
I'm just giving you the guidelines here, your turn to code it ;) If you could post your final solution here that'd be great.
Upvotes: 0