1. es5 实现
    1. function log1() {
    2. console.log("message 1")
    3. }
    4. function log2() {
    5. console.log("message 2")
    6. }
    7. function log1() {
    8. console.log("message 3")
    9. }
    10. function delay(fn, ms) {
    11. var timer, self;
    12. var queue
    13. function schedule(fn, ms) {
    14. timer = setTimeout(function() {
    15. timer = null
    16. fn()
    17. if (queue.length) {
    18. var item = queue.shift(item)
    19. schedule(item.fn, item.ms)
    20. }
    21. }, ms)
    22. }
    23. self = {
    24. delay: function(fn, ms) {
    25. if (queue,length || timer) {
    26. queue.push({fn, ms})
    27. } else {
    28. schedule(fn, ms)
    29. }
    30. return self;
    31. },
    32. cancel: function() {
    33. clearTimeout(timer)
    34. queue = []
    35. }
    36. }
    37. return self.delay(fn, ms)
    38. }
    39. var d = dalay(log1, 500).delay(log2, 1000).delay(log3, 2000)
    1. es6 实现
    1. function log1() {
    2. console.log("message 1")
    3. }
    4. function log2() {
    5. console.log("message 2")
    6. }
    7. function log1() {
    8. console.log("message 3")
    9. }
    10. function delay(fn, ms) {
    11. return new Promise(resolve => setTimeout(resolve, ms))
    12. }
    13. Promise.delay = function(fn, ms) {
    14. // fn is optional
    15. if (!ms) {
    16. ms = fn
    17. fn = function() {}
    18. }
    19. return delay(fn, ms).then(fn)
    20. }
    21. Promise.prototype.delay = function (fn, ms) {
    22. return this.then(() => {
    23. return Promise.delay(fn, ms)
    24. })
    25. }
    26. Promise.delay(log1, 500).delay(log2, 2000).delay(log3, 3000);
    27. // 使用async/await 优化
    28. async queueTask() {
    29. await Promise.delay(log1, 500)
    30. await Promise.delay(log2, 1500)
    31. await Promise.delay(log3, 2500)
    32. }
    33. queueTask()