Javascript JS如何为即时搜索添加延迟?
我的Html表单看起来像Javascript JS如何为即时搜索添加延迟?,javascript,angularjs,Javascript,Angularjs,我的Html表单看起来像 <form class="navbar-form navbar-left" role="search" name="userName"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search Git By Username" ng-model="user" ng-change="search
<form class="navbar-form navbar-left" role="search" name="userName">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search Git By Username" ng-model="user" ng-change="searchForUser()" autofocus>
</div>
</form>
我知道我可以使用ng model options=“{debounce:300}”,但我被要求学习$timeout以及如何在用户仍在键入时取消该事件。GitHub有一个速率限制,如果用户键入的速度太快,GitHub将返回http 403错误。下面是一种处理超时的方法
app.controller('MainCtrl', function ($scope, $timeout, $http) {
//keep a variable for storing timeoutPromise
var timeoutPromise;
$scope.searchForUser = function () {
$scope.selectedUser = null;
$scope.selectedRepo = null;
$scope.returnedRepos = [];
$scope.returnedCommits = [];
if ($scope.user.length === 0) {
$scope.returnedUsers = null;
return;
}
//if already a timeout is in progress cancel it
if (timeoutPromise) {
$timeout.cancel(timeoutPromise);
}
//Make a fresh timeout
timeoutPromise = $timeout(searchUsers, 500)
.finally(function(){
timeoutPromise = null; //nullify it
});
};
function searchUsers() {
$http.get("https://api.github.com/search/users?q=" + $scope.user).
success(function (data, status) {
if (status === 200) {
$scope.returnedUsers = data.items;
}
}).
error(function (data, status) {
alert("something happened with quhhnnhhhh");
});
}
});
我也会使用我,但我必须使用$timeout
app.controller('MainCtrl', function ($scope, $timeout, $http) {
//keep a variable for storing timeoutPromise
var timeoutPromise;
$scope.searchForUser = function () {
$scope.selectedUser = null;
$scope.selectedRepo = null;
$scope.returnedRepos = [];
$scope.returnedCommits = [];
if ($scope.user.length === 0) {
$scope.returnedUsers = null;
return;
}
//if already a timeout is in progress cancel it
if (timeoutPromise) {
$timeout.cancel(timeoutPromise);
}
//Make a fresh timeout
timeoutPromise = $timeout(searchUsers, 500)
.finally(function(){
timeoutPromise = null; //nullify it
});
};
function searchUsers() {
$http.get("https://api.github.com/search/users?q=" + $scope.user).
success(function (data, status) {
if (status === 200) {
$scope.returnedUsers = data.items;
}
}).
error(function (data, status) {
alert("something happened with quhhnnhhhh");
});
}
});