Я пытался реализовать эту проблему, используя очередь и запуск задач. Кто-нибудь может проверить, хорошо ли это выглядит, или мы можем улучшить его?
function $(selector) {
let element = document.querySelector(selector)
element.queue = []
element.active = false
return element
}
Element.prototype.next = function () {
if (this.queue.length) this.runTask(this.queue.shift())
}
Element.prototype.runTask = function (callBack) {
this.active = true
callBack().then(() => {
this.active = false
this.next()
})
}
Element.prototype.register = function(callBack){
if (this.active) {
this.queue.push(callBack)
} else {
this.runTask(callBack)
}
}
Element.prototype.addClass = function (className) {
that = this
let callBack = () => new Promise(resolve => setTimeout(function () {
that.classList.add(className)
resolve()
}, 0))
this.register(callBack)
return this
}
Element.prototype.removeClass = function (className) {
that = this
let callBack = () => new Promise(resolve => setTimeout(function () {
that.classList.remove(className)
resolve()
}, 0))
this.register(callBack)
return this
}
Element.prototype.delay = function (ms) {
that = this
let callBack = () => new Promise(resolve => setTimeout(function () {
resolve()
}, ms))
this.register(callBack)
return this
}
$('#test')
.removeClass("red").delay(500)
.addClass("blue").delay(500).delay(500).removeClass("blue")
.delay(500).addClass("red").delay(500).removeClass("red")
.delay(500).addClass("blue").delay(500).removeClass("blue")
.delay(500).addClass("red").delay(500).removeClass("red")
<!DOCTYPE html>
<html>
<head>
<style>
.blue{
background-color: blue;
}
.red{
background-color: red;
}
</style>
</head>
<body>
<div id="test" style="width: 150px; height: 150px; margin:10px;" class="red"></div>
</body>
</html>