js实用代码段(持续更新)

1.得到一个数,在一个有序数组中应该排在的位置序号:

function orderInArr(num,arr) {
  if(num > arr[0]){
    return 1 + arguments.callee(num,arr.slice(1))
  }else{
    return 0 
  }
}

//用法:
var arr = new Array(99,199,299,399);
alert(orderInArr(100,arr)
);//弹出的结果为:1;

 2.函数去抖debounce的简单实现:

var timer = null;
$(window).on('scroll',function(){
    if(timer){
        clearTimeout(timer);
        timer = null;                         
    }
    timer = setTimeout(function(){
        console.log('滑动结束')          
    },100)            
});
//该方法适用于scroll,mousemove,touchmove,resize等连续触发的事件;只触发事件完成后的一次;

3.函数节流throttle的简单实现:

var throttle = function(delay, action){
  var last = 0;
   return function(){
  
var curr = +new Date()  //将日期格式变为时间戳 if (curr - last > delay){
  action.apply(
this) last = curr }
}
}
var hehe = throttle(400,function(){  //函数闭包   console.log(123) }); $(window).on('scroll',hehe)
//该方法同样适用于scroll,mousemove,touchmove,resize等连续触发的事件;与debounce不同的是,该方法会不断触发,只是规定了事件触发的时间间隔;
//参考:http://www.cnblogs.com/fsjohnhuang/p/4147810.html
原文地址:https://www.cnblogs.com/hellobajie/p/5823435.html