(function($){ //CountDown var labels = ['days', 'hours', 'minutes', 'seconds'], template = _.template($('#main-coutndown-template').html()); // Parse countdown string to an object function strfobj(str) { var parsed = str.match(/([0-9]{2})/gi), obj = {}; labels.forEach(function(label, i) { obj[label] = parsed[i] }); return obj; } // Return the time components that diffs function diff(obj1, obj2) { var diff = []; labels.forEach(function(key) { if (obj1[key] !== obj2[key]) { diff.push(key); } }); return diff; } var currDate1 = '00:00:00:00', nextDate1 = '00:00:00:00'; var initData = strfobj(currDate1); var $mainCountdown1 = $('#mea-countdown-1'); labels.forEach(function(label, i) { $mainCountdown1.append(template({ curr: initData[label], label: label })); }); $mainCountdown1.countdown('2018/09/24 23:59:00', function(event) { var newDate = event.strftime('%D:%H:%M:%S'), data; if (newDate !== nextDate1) { currDate1 = nextDate1; nextDate1 = newDate; // Setup the data data = { 'curr': strfobj(currDate1), 'next': strfobj(nextDate1) }; // Apply the new values to each node that changed diff(data.curr, data.next).forEach(function(label) { var selector = '.%s'.replace(/%s/, label), $node = $mainCountdown1.find(selector); // Update the node $node.find('.curr').text(data.next[label]); }); } }); var currDate3 = '00:00:00:00', nextDate3 = '00:00:00:00'; var initData = strfobj(currDate3); var $mainCountdown3 = $('#mea-countdown-3'); labels.forEach(function(label, i) { $mainCountdown3.append(template({ curr: initData[label], label: label })); }); $mainCountdown3.countdown('2018/09/24 23:59:00', function(event) { var newDate = event.strftime('%D:%H:%M:%S'), data; if (newDate !== nextDate3) { currDate3 = nextDate3; nextDate3 = newDate; // Setup the data data = { 'curr': strfobj(currDate3), 'next': strfobj(nextDate3) }; // Apply the new values to each node that changed diff(data.curr, data.next).forEach(function(label) { var selector = '.%s'.replace(/%s/, label), $node = $mainCountdown3.find(selector); // Update the node $node.find('.curr').text(data.next[label]); }); } }); })(jQuery)