JavaScript 节流
程序员文章站
2022-05-14 13:27:48
...
JavaScript 节流
- 用户输入的节流
// An highlighted block
<script>
function method(med, api, async, data, callback) {
var http = new XMLHttpRequest();
if (med == "get") {
if (data) {
api += "?";
api += data;
}
http.open(med, api, async);
http.send();
}
else {
http.open(med, api, async);
if (data) {
http.send(data);
}
else {
http.send();
}
}
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
callback(http.response);
}
}
}
function getData(time,t){
return function (){
//清除计时器
clearTimeout(time);
time=setTimeout(function (){
method("post","./data.txt",true,"",function (result){
console.log(result);
});
},t);
}
}
var txt = document.getElementById("txt");
var time;
txt.addEventListener("keyup",getData(time,500));
</script>