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 = function(){
    if(this.baseline === undefined){
      this.baseline = new Date().getTime()
    var end = new Date().getTime()
    this.baseline += duration
    var nextTick = duration - (end - this.baseline)

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

this.stop = function(){

timer = new interval(step, function(){
    window.price = window.price - window.discountStep;

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

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

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.