重新延时运行的Js 实现

场景

1. AutoComplete 插件, 当用户的输入空闲0.5s 时,才向服务发送请求。而不是用户输入每一个字符都要请求服务器。

2. 图片懒加载时,用户拖动滚动条空闲0.5s时,才遍历懒加载的img元素,这样操作比较平滑。

原理

对每一个操作,定义一个唯一操作码,重新延时执行时,清空该操作码的执行体。重新定义延时执行体。

实现

    /*
        jv.RestartTimer("TextHelper",function(){ if ( this.die ) return false;})
    */
    jv.RestartTimer = function (key,func) {
        if (!window.restart_timer_dict) {
            window.restart_timer_dict = {};
        }
        
        if (window.restart_timer_dict[key])
        {
            window.restart_timer_dict[key].die = true;
            delete window.restart_timer_dict[key];
        }

        window.restart_timer_dict[key] = func;

        $.timer(500, function (timer) {
            timer.stop();
            window.restart_timer_dict[key]();
        });

 

你可能感兴趣的:(重新延时运行的Js 实现)