js 按照队列顺序执行函数,保证当前执行的函数不会被后面的函数覆盖。
/**
* 按照队列顺序执行函数
* @param fn
* @returns {function(...[*]=)}
*/
function queueFn(fn) {
const queue = [];
let running = false;
function next() {
if (running) return;
if (!queue.length) return;
running = true;
var args = queue.pop(), config = {millisecond: 3000};
config = Object.assign(config, args[0][1]);
try {
fn.call(this, args[0][0], config);
} catch (err) {
console.error(err)
}
setTimeout(function () {
running = false;
setTimeout(function () {
next();
}, 150);
}, config.millisecond);
}
return function (...args) {
queue.push([args, this]);
next();
}
}
/**
* 弹窗显示提醒消息
* @param str
* @param config
*/
function oppoMsg(str, config) {
if ($('#alertBox').length) {
$('#alertBox').remove();
}
str = '<div id="alertBox">' + str + '</div>';
$('body').append(str);
$('#alertBox').css({
'top': parseFloat((($(window).height()) / 2 + window.scrollY) * 9 / 10) + 'px',
'left': Math.floor(($(window).width() - $('#alertBox').outerWidth(true)) / 2) + 'px',
'zIndex': typeof config.zIndex == 'undefined' ? '' : config.zIndex
}).fadeIn('fast').delay(parseInt(config.millisecond)).fadeOut('fast', function () {
this.remove();
});
}
const queuedOppoMsg = queueFn(oppoMsg);
测试调用:
for (let i = 0; i < 3; i ++) {
queuedOppoMsg('第' + i + '个提醒', config);
}