Skip to content

Instantly share code, notes, and snippets.

@hectorguo
hectorguo / promiseAllWithLimit.js
Created December 6, 2018 22:39
Promise All with a max number of concurrent tasks
/**
* Run promise with a max number of concurrent tasks
* @param {Number} limit
*/
function promiseAllWithLimit(limit) {
let count = 0;
let queue = [];
const run = (fn, resolve, reject, ...args) => {
count++;
@hectorguo
hectorguo / throttle.js
Created November 14, 2018 06:36
throttle without using setTimeout (only last run)
function throttle(fn, rate) {
let oldTime;
let timer;
function helper(...args) {
const now = Date.now();
// first time: need to call fn once
if(!oldTime || now - oldTime > rate) {
@hectorguo
hectorguo / simple debounce.js
Created October 19, 2018 22:25
A simple debounce implementation
function debounce(fn, delay) {
let timer;
function helper(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args); // keep the original context
}, delay);
}
@hectorguo
hectorguo / setIntervalEx.js
Last active October 19, 2018 22:32
setInterval advanced version (using requestAnimationFrame to improve performance)
// requestAnimationFrame Polyfill for IE9
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
|| window[vendors[x]+'CancelRequestAnimationFrame'];
}
@hectorguo
hectorguo / getLocalIP.js
Last active March 18, 2024 06:21
Get local IP address through Javascript
/**
* Get Local IP Address
*
* @returns Promise Object
*
* getLocalIP().then((ipAddr) => {
* console.log(ipAddr); // 192.168.0.122
* });
*/
function getLocalIP() {
@hectorguo
hectorguo / BigNumber_lite.js
Last active August 30, 2022 03:07
print out big number in javascript (length > 22)
/**
* var big1 = new BigNum('234234234234234');
* var big2 = new BigNum('234234234234234');
* big1.multiplyBy(big2).toString(); // will output "54865676487297999188377566756" instead of 5.4865676487298e+28
*/
var BigNum = function(num) {
if (typeof num === 'string') {
this.parts = [];
while (num.length) {