實現(xiàn)一個邏輯:當(dāng)在input中輸入內(nèi)容的時候养距,將輸入的內(nèi)容顯示到一個div里面
html 文件
<input type="text" value=""/>
<div class="inputText"></div>
js文件
var count = 0
$("input").on("input",function(e){
count && clearTimeout(count)
count = setTimeout(function(){
$(".inputText").html( $(e.target).val())
}, 1000)
})
術(shù)語解釋
看完上面代碼和二,你肯定在平時工作中有用到過咯(沒有贫母?怎么可能7恰)
函數(shù)節(jié)流
定義:某個函數(shù)在一定時間間隔內(nèi)只執(zhí)行一次丰滑,也可以理解為把某個時間間隔內(nèi)執(zhí)行的函數(shù)合并為一個函數(shù)執(zhí)行
定義一個節(jié)流函數(shù)
定義一個函數(shù)名為throttle的函數(shù)
var count = null
function throttle (callback, delay) {
count && clearTimeout(count)
count = setTimeout(callback, delay)
}
$("input").on("input",function(e){
throttle(function(){
$(".inputText").html( $(e.target).val())
}, 1000)
})
上述函數(shù)有個問題,多了一個全局變量count倒庵,使用閉包改進一下函數(shù)
function throttle (callback, delay) {
var count = null
return (function() {
count && clearTimeout(count)
count = setTimeout(callback, delay)
})()
}
按理說這個函數(shù)已經(jīng)很完美了褒墨,但是只是理論上的完美炫刷,在實際操作中會出現(xiàn)一種情況,如上例:輸入框一直在輸入文字郁妈,文字就一直不會顯示出來浑玛。我們需要做一個處理:使得文字在超過某個時間間隔后要輸出一次。
function throttle (callback, delay, wait) {
var count = null
var start = null
return function() {
var now = +new Date()
var context = this
var args = arguments
if ( !start ) {
start = now
}
if ( now - start > wait ) {
count && clearTimeout(count)
start = now
callback.apply(this, args)
} else {
count && clearTimeout(count)
count = setTimeout(function(){
callback.apply(this, args)
}, delay)
}
}
}
var f = throttle(function(e){
$(".inputText").html($(e.target).val())
}, 1000, 2000)
$("input").on("input",function(e){
f(e)
})