手写实现冒泡排序,防抖,节流,事件总线(eventBus)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> //冒泡排序 function bubbleSort(array) { if (array && array.length > 0) { for (let i = 0; i < array.length - 1; i++) { for (let j = 0; j < array.length - i - 1; j++) { if (array[j] > array[j + 1]) { let temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } } } let array = [4, 1, 6, 8, 2, 5, 9]; bubbleSort(array) //防抖 function debounce(fn, delay) { let time = null return function (...arg) { clearTimeout(time) time = setTimeout(() => { fn.apply(this, arg) }, delay) } } // 节流 function throttle(fn, delay) { let flag = true return function (...args) { if (!args) return; flag = false; setTimeout(() => { fn.apply(this, args) flag = true; }, delay); } } class EventBus { constructor() { this.listeners = {}; } // 订阅事件 on(event, callback) { if (!this.listeners[event]) { this.listeners[event] = []; } this.listeners[event].push(callback); } // 触发事件 emit(event, ...args) { if (this.listeners[event]) { this.listeners[event].forEach(callback => callback(...args)); } } // 取消订阅事件 off(event, callback) { if (this.listeners[event]) { this.listeners[event] = this.listeners[event].filter(cb => cb !== callback); } } } // 使用示例 const eventBus = new EventBus(); // 订阅事件 eventBus.on('userLoggedIn', (user) => { console.log(`User logged in: ${user}`); }); // 触发事件 eventBus.emit('userLoggedIn', 'JohnDoe'); </script> </body> </html>