I suppose this is an easy problem to solve, it’s just a little bit tricky to google. I have this function that random generates some numbers for 1 second until it reaches the real value (number()), just a flashy effect. However, the value is a 7 digit number and I want to separate it with commas. I have working functions for both of the functions but I dont know how to make them work together. I’ve tried to add the digits() function to my number() function but I cant get the commas to show while the number is random generating, only when it’s done.
This is my number() code:
(function($){
$.fn.extend({
number: function(options) {
if ( ! this.length)
return false;
this.defaults = {
endAt: 90,
numClass: 'autogen-num',
interval: 65 // ms
};
var settings = $.extend({}, this.defaults, options);
var $num = $('<span/>', {
'class': settings.numClass
});
return this.each(function() {
var $this = $(this);
// Wrap each number in a tag.
var frag = document.createDocumentFragment(),
numLen = settings.endAt.toString().length;
for (x = 0; x < numLen; x++) {
var rand_num = Math.floor( Math.random() * 10 );
frag.appendChild( $num.clone().text(rand_num)[0] )
}
$this.empty().append(frag);
var get_next_num = function(num) {
++num;
if (num > 9) return 0;
return num;
};
// Iterate each number.
$this.find('.' + settings.numClass).each(function() {
var $num = $(this),
num = parseInt( $num.text() );
var interval = setInterval( function() {
num = get_next_num(num);
$num.text(num);
}, settings.interval);
setTimeout( function() {
clearInterval(interval);
}, settings.duration * 1000 - settings.interval);
});
setTimeout( function() {
$this.text( settings.endAt.toString() );
}, settings.duration * 1000);
});
}
});
})(jQuery);
And this is my digits() code:
$.fn.digits = function(){
return this.each(function(){
$(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
})
}
Thanks in advance!
The numbers function replaces only one number at the time, and it relies on the numbers being numbers, so replacing them during the loop with a string containing commas is’nt really an option!
I rebuilt the numbers function to handle a string instead. No idea if it’s what you’re looking for, but it’s the closest I could get:
FIDDLE