没有函数防抖的效果
<! DOCTYPE html >
< html lang = " zh" >
< head>
< meta charset = " UTF-8" />
< meta name = " viewport" content = " width=device-width, initial-scale=1.0" />
< title> Document</ title>
</ head>
< body>
< input type = " text" id = " username" />
< script src = " ./libs/jquery/jquery.js" > </ script>
< script>
$ ( '#username' ) . on ( 'input' , function ( ) {
let str = $ ( this ) . val ( )
$. ajax ( {
type: 'get' ,
url: 'http://127.0.0.1:3001/validate' ,
data: {
userName: str
} ,
success : res => {
console. log ( res)
}
} )
} )
</ script>
</ body>
</ html>
添加了函数防抖的效果
<! DOCTYPE html >
< html lang = " zh" >
< head>
< meta charset = " UTF-8" />
< meta name = " viewport" content = " width=device-width, initial-scale=1.0" />
< title> Document</ title>
</ head>
< body>
< input type = " text" id = " username" /> < span class = " msg" > </ span>
< script src = " ./libs/jquery/jquery.js" > </ script>
< script>
let timeid = null
$ ( '#username' ) . on ( 'input' , function ( ) {
let str = $ ( this ) . val ( )
if ( timeid) {
clearTimeout ( timeid)
}
timeid = setTimeout ( ( ) => {
$. ajax ( {
type: 'get' ,
url: 'http://127.0.0.1:3001/validate' ,
data: {
userName: str
} ,
success : res => {
console. log ( res)
$ ( '.msg' ) . text ( res. msg)
}
} )
} , 2000 )
} )
</ script>
</ body>
</ html>
未添加节流
<! DOCTYPE html >
< html lang = " zh" >
< head>
< meta charset = " UTF-8" />
< meta name = " viewport" content = " width=device-width, initial-scale=1.0" />
< title> Document</ title>
</ head>
< body>
< h1> 节流</ h1>
< button> 获取数据</ button>
< script src = " ./libs/jquery/jquery.js" > </ script>
< script>
let time = null
$ ( 'button' ) . on ( 'click' , function ( ) {
if ( time) {
return
}
time = setTimeout ( ( ) => {
$. ajax ( {
url: 'http://127.0.0.1:3001/getStudentsJSONDelay' ,
success : function ( res ) {
console. log ( res)
} ,
complete : function ( ) {
time = null
}
} )
} , 0 )
} )
</ script>
</ body>
</ html>
bool值实现节流 / loading效果
<! DOCTYPE html >
< html lang = " zh" >
< head>
< meta charset = " UTF-8" />
< meta name = " viewport" content = " width=device-width, initial-scale=1.0" />
< title> Document</ title>
</ head>
< body>
< h1> 节流</ h1>
< button> 获取数据</ button>
< script src = " ./libs/jquery/jquery.js" > </ script>
< script>
let loading = false
$ ( 'button' ) . on ( 'click' , function ( ) {
if ( loading) {
return
}
$. ajax ( {
url: 'http://127.0.0.1:3001/getStudentsJSONDelay' ,
beforeSend : function ( ) {
loading = true
} ,
success : function ( res ) {
console. log ( res)
} ,
complete : function ( ) {
loading = false
}
} )
} )
</ script>
</ body>
</ html>