Skip to content

[js] 第432天 说说防止重复发送ajax请求的方法有哪些?各自有什么优缺点? #2543

@haizhilin2013

Description

@haizhilin2013
Collaborator

第432天 说说防止重复发送ajax请求的方法有哪些?各自有什么优缺点?

3+1官网

我也要出题

Activity

longhui520

longhui520 commented on Jun 21, 2020

@longhui520
  • 防抖法:在一段时间内重复请求,则取消本次请求
  • 节流法:在一段时间内只能请求一次,下次请求必须在前一次请求完成后
  • 等值法:未完成请求状态不再请求,而是完成后直接返回相同的内容
yangyi1987

yangyi1987 commented on Oct 6, 2020

@yangyi1987

// 方法一 防抖

function debounce(f, ms) {
let time;
return function(){
let arg = Array.prototype.slice.call(arguments, 1);
if(time) {
clearTimeout(time);
}
time = setTimeout(function(){
f.apply(this, arg)
},ms)
}
}

// 方法二 节流
function throttle(f, ms){
let lastTime = 0;
return function(){
let arg = Array.prototype.slice.call(arguments, 1);
let newTime = Date.now();
if(newTime-lastTime > ms) {
setTimeout(function(){
f.apply(this, arg)
},ms)
}
lastTime = newTime;
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@longhui520@yangyi1987

        Issue actions

          [js] 第432天 说说防止重复发送ajax请求的方法有哪些?各自有什么优缺点? · Issue #2543 · haizlin/fe-interview