第三个参数为是否取消延时
???function debounce (func, wait, immediate) { ?????var timeout, result; ?????var debounced = ?function () { ???????var context = this ?// 找回this ???????var arg = arguments // 找回event对象 ???????if (timeout) clearTimeout(timeout); ???????if (immediate) { ?????????var callNow = !timeout; ?????????timeout = setTimeout(function () { ???????????timeout = false; ?????????}, wait) ?????????if (callNow) result = func.apply(context, arg); ???????} else { ???????????timeout = setTimeout(function () { ???????????result = func.apply(context, arg) ?????????}, wait) ???????} ???????return result // 如果函数有返回值 ?????} ?????// 第三个参数设置为true,在等待的时候 ?????// 我希望立即执行 ?????// 暴露出去 ?????debounced.cancel = function () { ???????clearTimeout(timeout) ???????timeout = false ?????} ?????return debounced ???}