我正在尝试创建一个按钮,以便在他被单击后立即执行操作。但是,如果在超时后鼠标仍处于按下状态,则只要按钮处于按下状态,就应重复该操作。
在以下代码中,$ interval正在运行。但是以某种方式,$ timeout会被忽略,并且间隔立即开始。我在做什么错了?
angular
.module('myApp', [])
.controller('myController', ($scope, $timeout, $interval) => {
var interval;
var timeout;
let main = $scope;
main.times = 0;
let promise;
let doSomethingOneTime = () => {
$scope.times++;
};
let doSomethingInfinitely = function() {
promise = $interval(function() {
doSomethingOneTime();
}, 100)
};
main.mouseDown = function(action) {
doSomethingOneTime();
$timeout(doSomethingInfinitely, 5000);
};
main.mouseUp = function() {
$interval.cancel(promise);
};
});
<!DOCTYPE html>
<html ng-app='myApp'>
<head>
<script data-require="angular.js@4.0.0" data-semver="4.0.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.10/angular.min.js"></script>
<script data-require="angular.js@4.0.0" data-semver="4.0.0" src="script.ts"></script>
<script data-require="angular.js@4.0.0" data-semver="4.0.0" src="system.config.js"></script>
<script data-require="angular.js@4.0.0" data-semver="4.0.0" src="tsconfig.json"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller='myController'>
<button ng-mousedown="mouseDown()" ng-mouseup="mouseUp()">Mouse Down</button>
<br>
<span>Doing something {{times}} times</span>
</body>
</html>
答案 0 :(得分:1)
问题是两个方面。第一种情况是,如果您在超时延迟结束之前将鼠标悬停在上方,则您设置的间隔承诺仍将是不确定的,因此,当您调用取消时,不会取消任何内容。第二个问题是,如果您单击两次按钮,您将失去对第一个间隔承诺的所有参考。第二次单击将创建第二个超时,完成后将替换第一个间隔承诺。实际上,您将同时执行2个$ interval,其中之一没有引用。
这是一个可行的示例。
public class Places extends RecyclerView.ViewHolder {
private String lat;
private String lon;
public Places(View itemView) {
super(itemView);
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLon() {
return lon;
}
public void setLon(String lon) {
this.lon = lon;
}
}
public class Places extends RecyclerView.ViewHolder {
private String lat;
private String lon;
public Places(View itemView) {
super(itemView);
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLon() {
return lon;
}
public void setLon(String lon) {
this.lon = lon;
}
}