简体   繁体   中英

Find curve between two lines in javascript

I have a counter counting votes. However, I'm only pulling the number ever 30 seconds from the server. I'd like it to look fairly consistent on the front end, so I've written a little script to keep track of the increases and give it a nice linear increase in votes, multiple times per second.

However, I can't seem to transition between different rates very well - my brain locks up getting past linear.

Example: Lets say we're at 100 votes.

The votes are predicted to increase by 60 over the next 30 seconds, or on a 2 votes per 1 second (2/1). I can get that far already.

We end up 30 seconds later with 160 votes from our linear gain.

Now, the next segment is predicted to increase by only 20 over 30 seconds, or 2 votes per 3 seconds (2/3).

Rather than have a sudden drop in vote rate, I'd like a smooth transition in rate where 30 seconds later I'll have the correct (180) total votes, the counter decelerating (or accelerating, accordingly) rather than just suddenly changing linear gains.

var t = 0;
function upCount(){
  $("#votecount").text(Math.floor(current + nextInc*(t/60));
  t++;
}

current is the current number of votes as reported from the server, and nextInc is the predicted number of votes to occur over the next 30 seconds.

t is "time", reset to zero with each ajax pull from the server. This is inside an interval of 500ms.

Maybe I'm going about it all wrong. Crazy ideas welcome. I am allowed to use jQuery here, if it helps.

Thanks!

How about applying an exponential filter to your rates? That is

smoothed_rate = (current_rate + c*smoothed_rate) / (1+c)

This gives you a parameter c to tune the smoothing. c=0 --> no smoothing at all. larger c --> more smoothing.

If you want to smooth out the rate changes as well, then introduce more points. You need no additional server roundtrips. Just replicate what you got. Eg if you compute a rate x for 30 seconds, then assume 3 intervalls with rate x for 10 seconds and apply the smoothing to them. This gives you higher order smoothing with almost no additional efforts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM