Skip to content

Instantly share code, notes, and snippets.

@nuintun
Last active March 11, 2021 02:08
Show Gist options
  • Save nuintun/ad267bdb3ca786f30993 to your computer and use it in GitHub Desktop.
Save nuintun/ad267bdb3ca786f30993 to your computer and use it in GitHub Desktop.
在一个元素节点生成一个锁,保证在没有解锁的时候回调不会执行!

源码

(function ($){
  $.fn.sync = function (lock, fn){
    // 初始化参数
    fn = arguments.length === 1 ? lock : fn;
    fn = typeof lock === 'function' ? fn : $.noop;
    lock = lock && typeof lock === 'string' ? lock : 'default';
    lock = 'data-sync-' + lock;

    return this.each(function (){
      // 获取节点元素
      var sync = $(this);

      // 如果已经上锁不做处理
      if (sync.data(lock)) return;

      // 打开同步锁
      sync.data(lock, true);

      // 执行回调并传入解锁函数
      fn.call(this, function (){
        sync.data(lock, false);
      });
    });
  };
}(jQuery));

用法 以下代码只能3秒钟执行一次,同步期间多次点击不会重复执行,直到调用async函数进行异步解锁后才能再次执行!

$('#sync').on('click', function (){
  $(this).sync(function (async){
    console.log('sync');

    // 3秒后解锁,async名称可以自定义
    setTimeout(function (){
      async();
      console.log('async');
    }, 3000);
  });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment