Skip to content

debounce示例写法有点欠妥 #194

@Bjkb

Description

@Bjkb

image
测试将immediate置为false,后面的函数变量没有被保存

测试用例:

function testFn(name){
  console.log(`hello ${name}`);
}
var d = debounce(testFn,0,false);
d('xiaomin');
d('xiaohua');
-----> hello xiaomin  // 置为false,应该输出 hello xiaohua

稍加修改

 return function(...params) {
     // 否则缓存参数和调用上下文
     // 更改的地方
     context = this
     args = params
    // 如果没有创建延迟执行函数(later),就创建一个
    if (!timer) {
      timer = later()
      // 如果是立即执行,调用函数
      if (immediate) {
        func.apply(this, params)
      }
    // 如果已有延迟执行函数(later),调用的时候清除原来的并重新设定一个
    // 这样做延迟函数会重新计时
    } else {
      clearTimeout(timer)
      timer = later()
    }
  }

// 测试用例输出 -----> hello xiaohua

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions