(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/06/18 08:00: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 currDate2 = '00:00:00:00', nextDate2 = '00:00:00:00'; var initData = strfobj(currDate2); var $mainCountdown2 = $('#mea-countdown-2'); labels.forEach(function(label, i) { $mainCountdown2.append(template({ curr: initData[label], label: label })); }); $mainCountdown2.countdown('2018/06/22 23:59:00', function(event) { var newDate = event.strftime('%D:%H:%M:%S'), data; if (newDate !== nextDate2) { currDate2 = nextDate2; nextDate2 = newDate; // Setup the data data = { 'curr': strfobj(currDate2), 'next': strfobj(nextDate2) }; // Apply the new values to each node that changed diff(data.curr, data.next).forEach(function(label) { var selector = '.%s'.replace(/%s/, label), $node = $mainCountdown2.find(selector); // Update the node $node.find('.curr').text(data.next[label]); }); } }); })(jQuery)