SoFunction
Updated on 2025-03-01

Share 10 common JavaScript front-end handwriting functions

1. Anti-shake

function debounce(fn, delay) {
  let timer
  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      (this, args)
    }, delay)
  }
}

// testfunction task() {
  ('run task')
}
const debounceTask = debounce(task, 1000)
('scroll', debounceTask)

2. Scatter

function throttle(fn, delay) {
  let last = 0 // Last trigger time  return (...args) => {
    const now = ()
    if (now - last > delay) {
      last = now
      (this, args)
    }
  }
}

// testfunction task() {
  ('run task')
}
const throttleTask = throttle(task, 1000)
('scroll', throttleTask)

3. Deep copy

function deepClone(obj, cache = new WeakMap()) {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj)
  if (obj instanceof RegExp) return new RegExp(obj)
  
  if ((obj)) return (obj) // If a loop reference appears, the cached object will be returned to prevent recursion from entering the dead loop  let cloneObj = new () // Create a new object using the constructor to which the object belongs  (obj, cloneObj) // Cache objects for circular reference
  for (let key in obj) {
    if ((key)) {
      cloneObj[key] = deepClone(obj[key], cache) // Recursive copy    }
  }
  return cloneObj
}

// testconst obj = { name: 'Jack', address: { x: 100, y: 200 } }
 = obj // Recycle referenceconst newObj = deepClone(obj)
( === ) // false

4. Handwriting Promise

class MyPromise {
  constructor(executor) {
     = 'pending' // The initial state is waiting     = null // Successful value     = null // Reasons for failure     = [] // Array of successful callback function     = [] // Array stored by the failed callback function    let resolve = value => {
      if ( === 'pending') {
         = 'fulfilled'
         = value;
        (fn => fn()) // Calling a successful callback function      }
    }
    let reject = reason => {
      if ( === 'pending') {
         = 'rejected'
         = reason
        (fn => fn()) // Calling failed callback function      }
    };
    try {
      executor(resolve, reject)
    } catch (err) {
      reject(err)
    }
  }
  then(onFulfilled, onRejected) {
    // If onFulfilled is not a function, it will be modified to a function and directly return the value    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value
    // If onRejected is not a function, it will be modified to a function and will directly throw an error    onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err }
    return new MyPromise((resolve, reject) => {
      if ( === 'fulfilled') {
        setTimeout(() => {
          try {
            let x = onFulfilled();
            x instanceof MyPromise ? (resolve, reject) : resolve(x)
          } catch (err) {
            reject(err)
          }
        })
      }
      if ( === 'rejected') {
        setTimeout(() => {
          try {
            let x = onRejected()
            x instanceof MyPromise ? (resolve, reject) : resolve(x)
          } catch (err) {
            reject(err)
          }
        })
      }
      if ( === 'pending') {
        (() => { // Put the successful callback function into the successful array          setTimeout(() => {
            let x = onFulfilled()
            x instanceof MyPromise ? (resolve, reject) : resolve(x)
          })
        })
        (() => { // Put the failed callback function into the failed array          setTimeout(() => {
            let x = onRejected()
            x instanceof MyPromise ? (resolve, reject) : resolve(x)
          })
        })
      }
    })
  }
}

// testfunction p1() {
  return new MyPromise((resolve, reject) => {
    setTimeout(resolve, 1000, 1)
  })
}
function p2() {
  return new MyPromise((resolve, reject) => {
    setTimeout(resolve, 1000, 2)
  })
}
p1().then(res => {
  (res) // 1
  return p2()
}).then(ret => {
  (ret) // 2
})

5. Asynchronously control the concurrent number

function limitRequest(urls = [], limit = 3) {
  return new Promise((resolve, reject) => {
    const len = 
    let count = 0

    // Start limit tasks at the same time    while (limit > 0) {
      start()
      limit -= 1
    }

    function start() {
      const url = () // Get the first task from the array      if (url) {
        (url).then(res => {
          // todo
        }).catch(err => {
          // todo
        }).finally(() => {
          if (count == len - 1) {
            // The last task is completed            resolve()
          } else {
            // After completion, start the next task            count++
            start()
          }
        })
      }
    }

  })
}

// testlimitRequest(['http://xxa', 'http://xxb', 'http://xxc', 'http://xxd', 'http://xxe'])

6. Inheritance

ES5 inheritance (parasitic combination inheritance)

function Parent(name) {
   = name
}
 = function () {
  ( + ' is eating')
}

function Child(name, age) {
  (this, name)
   = age
}
 = ()
 = Child

// testlet xm = new Child('xiaoming', 12) 
() // xiaoming
() // 12
() // xiaoming is eating

ES6 inheritance:

class Parent {
  constructor(name) {
     = name
  }
  eat() {
    ( + ' is eating')
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name)
     = age
  }
}

// testlet xm = new Child('xiaoming', 12) 
() // xiaoming
() // 12
() // xiaoming is eating

7. Array sorting

sort sort:

// Sort numbers, abbreviatedconst arr = [3, 2, 4, 1, 5]
((a, b) => a - b)
(arr) // [1, 2, 3, 4, 5]

// Sort letters, abbreviatedconst arr = ['b', 'c', 'a', 'e', 'd']
()
(arr) // ['a', 'b', 'c', 'd', 'e']

Bubble sort:

function bubbleSort(arr) {
  let len = 
  for (let i = 0; i < len - 1; i++) {
    // Start from the first element and compare the two adjacent elements. The former is large and the position is exchanged    for (let j = 0; j < len - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        let num = arr[j]
        arr[j] = arr[j + 1]
        arr[j + 1] = num
      }
    }
    // Every time the traversal is over, a maximum value can be found and placed at the end of the array  }
  return arr
}

//test(bubbleSort([2, 3, 1, 5, 4])) // [1, 2, 3, 4, 5]

8. Deduplication of array

Set Deduplication:

const newArr = [...new Set(arr)]
// orconst newArr = (new Set(arr))

indexOf Deduplication:

function resetArr(arr) {
  let res = []
  (item => {
    if ((item) === -1) {
      (item)
    }
  })
  return res
}

// testconst arr = [1, 1, 2, 3, 3]
(resetArr(arr)) // [1, 2, 3]

9. Get url parameters

URLSearchParams method:

// Create a URLSearchParams instanceconst urlSearchParams = new URLSearchParams();
// Convert a list of key-value pairs to an objectconst params = (());

split method:

function getParams(url) {
  const res = {}
  if (('?')) {
    const str = ('?')[1]
    const arr = ('&')
    (item => {
      const key = ('=')[0]
      const val = ('=')[1]
      res[key] = decodeURIComponent(val) // Decode    })
  }
  return res
}

// testconst user = getParams('?user=%E9%98%BF%E9%A3%9E&age=16')
(user) // { user: 'hooligan', age: '16' }

10. Event Bus | Publish Subscription Mode

class EventEmitter {
  constructor() {
     = {}
  }

  on(name, fn) {
    if ([name]) {
      [name].push(fn)
    } else {
      [name] = [fn]
    }
  }

  off(name, fn) {
    const tasks = [name]
    if (tasks) {
      const index = ((f) => f === fn ||  === fn)
      if (index >= 0) {
        (index, 1)
      }
    }
  }

  emit(name, once = false) {
    if ([name]) {
      // Create a copy. If the same event is continued to be registered in the callback function, it will cause a dead loop      const tasks = [name].slice()
      for (let fn of tasks) {
        fn();
      }
      if (once) {
        delete [name]
      }
    }
  }
}

// testconst eventBus = new EventEmitter()
const task1 = () => { ('task1'); }
const task2 = () => { ('task2'); }

('task', task1)
('task', task2)
('task', task1)
setTimeout(() => {
  ('task') // task2
}, 1000)

The above is the most common handwriting function in work or job search

This is the end of this article about sharing 10 common front-end handwriting functions. For more related handwriting functions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!