Just few days back i got a request for my client to making a script that Increment Number with random interval. Then i thought to make a small plugin that generates random interval. How it works, is start number increments with a default value (1000) and set a cookie to user’s browser and every time this script update the cookies value so that when the user refresh there browser he/she get the same last incremented value. You can control the setTimeout random interval to change the value in the following line var rand = Math.round(Math.random() * (2000 - 200)) + 200;
Insert following Script:
Here is how you have to implemented this script on your website. Just insert the below javascript plugin into the ....
tag or before the closed tag. No external javascript library is required for the plugin.
var numGenrator = function(element){ this.element = document.getElementById(element); }; numGenrator.prototype = { init: function(options){ var that = this; that.tempRange = options.startRange == undefined ? 1000 : options.startRange; that.range = that.readCookie('_jnum') == null ? that.tempRange : that.readCookie('_jnum'); that.format = options.currencyFormat == undefined ? false : options.currencyFormat; // Default Value that.element.innerHTML = that.format == true ? this.currencyFormat( that.range ) : that.range; (function loop() { var rand = Math.round(Math.random() * (8000 - 200)) + 700; setTimeout(function() { that.actionInit(); loop(); }, rand); }()); }, actionInit: function(){ this.range++; // Use Cookie to Remmber // Last Value this.createCookie('_jnum', this.range, 20); this.element.innerHTML = this.format == true ? this.currencyFormat( this.range ) : this.range; }, createCookie: function(name, value, days){ if( days ){ var date = new Date; date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expire = "; expires=" + date.toGMTString(); } else { var expire = ""; } document.cookie = name + "=" + value + expire + "; path=/"; }, readCookie: function(name){ var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; }, eraseCookie: function(name){ this.createCookie(name, "", -1); }, currencyFormat: function(num){ return num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); } };
How to use Random Interval Script?
After inserted the above plugin, use the following code below the plugin inserted.
window.onload = function(){ var randNumber = new numGenrator( 'result' ); randNumber.init({ startRange: 9845620, // Default is 1000 currencyFormat: true }); }
Here is the working fiddle you can find on http://jsfiddle.net/jogesh_pi/SKFay/