Fast price count down on javascript

If you need simple price count down for your web site it’s easy realized on javascript. We can use setInterval() function for this purpose. But if you need fast count down, e.g. decrease high price for 1 cent per step that time interval for setInterval() function will be too small. So we have two trouble with small time interval (less then 200 ms). First is that setInterval() function doesn’t have time to work on each tick. And when you set focuse to another tab of you browser, setInterval() function stops or slows down. It’s the second trouble.
Code below can resolve first problem. It’s much faster then setInterval() function

function interval(duration, fn){
  this.baseline = undefined
  
  this.run = function(){
    if(this.baseline === undefined){
      this.baseline = new Date().getTime()
    }
    fn()
    var end = new Date().getTime()
    this.baseline += duration
 
    var nextTick = duration - (end - this.baseline)

		if(nextTick<0){
		  nextTick = 0
		} else  if(document.hasFocus){
			(function(i){
				i.timer = setTimeout(function(){
				i.run(end)
			  }, nextTick)
			}(this))
		}
	}
  

this.stop = function(){
   clearTimeout(this.timer)
 }
}

timer = new interval(step, function(){
    window.price = window.price - window.discountStep;
    $("#price_value").text(parseFloat(window.price).toFixed(2));
})
timer.run();

For solving second problem we need stop countdown, synchronize price value and start count down again when focus return on tab with our count down

   window.onfocus=function(event){
      $.getJSON(window.daemonHost+"/ajax/synchprice?jsonp_callback=?", function(data){
							if(data > 0){
								timer.stop();
								window.price = data;
								timer = new interval(step, function(){
									window.price = window.price - window.discountStep;									      $("#price_value").text(parseFloat(window.price).toFixed(2));
								});
								timer.run();
							}	
						},"json");
					}
				}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.