代码
/**
* 调用回调函数
* @param callback 回调函数体
* @param args 参数
*/
execCallback: function (callback, args) {
if (callback != null
&& typeof (callback) === 'function'
&& callback instanceof Function
&& Object.prototype.toString.call(callback) === '[object Function]'
) {
callback(args)
}
}
/**
* 倒计时
* @param options.time 开始倒计时的时间
* @param options.setup 每次倒计时回调
* @param options.end 结束时回调
*/
countdown: (options) => {
options.time = options.time || 0;
options.setup = options.setup || ((num) => console.info('countdown:setup:' + num));
options.end = options.end || ((num) => console.info('countdown:end:' + num));
if (!config.isEmpty(options.time)) {
// 倒计时
let num = parseInt(options.time);
let tim = setInterval(() => {
if (num <= 0) {
clearInterval(tim);
execCallback(options.end, num);
} else {
num--;
execCallback(options.setup, num);
}
}, 1000);
}
}
实例:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>倒计时</title>
</head>
<body>
<h1 id="date"></h1>
<script>
/**
* 调用回调函数
* @param callback 回调函数体
* @param args 参数
*/
function execCallback(callback, args) {
if (callback != null
&& typeof (callback) === 'function'
&& callback instanceof Function
&& Object.prototype.toString.call(callback) === '[object Function]'
) {
callback(args)
}
}
/**
* 倒计时
* @param options.time 开始倒计时的时间
* @param options.setup 每次倒计时回调
* @param options.end 结束时回调
*/
function countdown(options) {
options.time = options.time || 0;
options.setup = options.setup || ((num) => console.info('countdown:setup:' + num));
options.end = options.end || ((num) => console.info('countdown:end:' + num));
// 倒计时
let num = parseInt(options.time);
let tim = setInterval(() => {
if (num <= 0) {
clearInterval(tim);
execCallback(options.end, num);
} else {
num--;
execCallback(options.setup, num);
}
}, 1000);
}
// 使用
countdown({
time: 15,
setup: (num) => {
document.getElementById("date").innerHTML = `时间末日将在 ${num}秒 后来临!!!`;
},
end: (num) => {
document.getElementById("date").innerHTML = "哈哈,骗你的。";
}
});
</script>
</body>
</html>