Skip to content

Instantly share code, notes, and snippets.

@anhulife
Last active December 18, 2015 22:49
Show Gist options
  • Save anhulife/5857253 to your computer and use it in GitHub Desktop.
Save anhulife/5857253 to your computer and use it in GitHub Desktop.
倒计时
var countDown = (function($){
var counts = {}, countTime, stopped = true, id = 0;
function count(){
var length = 0;
$.each(counts, function(key, countObj){
var timeObj, seconds = countObj.seconds - ((new Date().getTime() - countObj.startTime) /1000);
if(seconds > 0){
timeObj = {
seconds: parseInt(seconds % 60, 10),
minutes: parseInt((seconds / 60) % 60, 10),
hours: parseInt((seconds / 60 / 60) % 24, 10),
days: parseInt(seconds / 60 / 60 / 24, 10)
};
length++;
}else{
delete counts[key];
}
setTimeout(function(){countObj.callback(seconds, timeObj);}, 0);
});
if(length === 0){
stop();
}
}
function add(seconds, callback){
var _id = 'count'+(id++);
counts[_id] = {seconds: seconds, callback: callback, startTime: new Date().getTime()};
start();
return _id;
}
function stop(){
window.clearInterval(countTime);
stopped = true;
}
function start(){
if(stopped){
countTime = window.setInterval(count, 500);
stopped = false;
}
}
return {add: add, stop: stop, start: start};
})(jQuery);
countDown.add(200, function(seconds, timeObj){console.log('first:', seconds, timeObj);});
countDown.add(150, function(seconds, timeObj){console.log('second:', seconds, timeObj);});
countDown.add(100, function(seconds, timeObj){console.log('third:', seconds, timeObj);});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment