设置超时 在设置超时未触发

SetTimeout inside SetTimeout not firing

本文关键字:设置 超时      更新时间:2023-09-26

我正在尝试创建一个按钮,该按钮为其正在执行的操作提供反馈。在 Angular 中,我向服务器发出一个 put 请求 - 此时我更改按钮的状态以指示这一点 - 然后当我收到响应时,我再次更改按钮的状态以反映成功或失败 1.5 秒,然后将其重置回单击按钮之前的原始状态。此时还会显示一条消息以反映成功或失败,再过 5 秒后应执行其他操作。如果显示的消息失败,则应隐藏,如果成功,则应重定向页面。这是最后一部分,我没有开始工作。

因此,我的问题是我是否应该能够在另一个设置超时中放置一个设置超时?

这是我的代码(在按钮的函数内(:

$scope.resetPassword = function() {
    $scope.ShowSuccessMessage = false;
    $scope.ShowFailedMessage = false;
    var querystring = $location.search();
    var dataObject = { email1 : $scope.formEmail1, email2 : $scope.formEmail2, password1: $scope.formPassword1, password2: $scope.formPassword2, token: querystring.token };
    var responsePromise = $http.put("/myurl/", dataObject, {});
    //  change colour and icon of reset button for 1.5 sec
    var $el           = $("#resetPassword");
    var resetButton   = 1500;
    var resetMessage  = 5000;
    var originalColor = $el.css("background");
    var originalIcon  = $el[0].firstChild.className; // get first html element in the button, which is the <i>
    $el[0].firstChild.className = "fa fa-circle-o-notch fa-spin";
    responsePromise.success(function(dataFromServer, status, headers, config) {
      $el.css("background", "#02c66c");
      $el[0].firstChild.className = "fa fa-check-circle";
      $scope.ShowSuccessMessage = true;
      ResetButton($el, $scope, originalColor, originalIcon, resetButton, true, resetMessage);
    });
    responsePromise.error(function(dataFromServer, status, headers, config) {
      $el.css("background", "#d9534f");
      $el[0].firstChild.className = "fa fa-times-circle";
      $scope.ShowFailedMessage = true;
      ResetButton($el, $scope, originalColor, originalIcon, resetButton, false, resetMessage);
    });
};
ResetButton = function(el, scope, originalColor, originalIcon, resetButton, success, resetMessage)
{
  setTimeout(function() {
    el.css("background", originalColor);
    el[0].firstChild.className = originalIcon;
    ChangeMessageOrChangeLocation(scope, success, resetMessage);
  }, resetButton);
}
ChangeMessageOrChangeLocation = function(scope, success, resetMessage)
{
  if(success) {
    setTimeout(function(){
      window.location = '/signin';
    }, resetMessage);
  }
  else {  
    setTimeout(function() {
      scope.ShowFailedMessage = false;
    }, resetMessage);
  }
}

编辑:这是一个活生生的例子:贪婪的喜鹊(请记住,这是一项正在进行的工作,因此并非网站上的所有内容都可以正常工作。只需单击更改密码按钮...

winfow.setTimeout 在 Angular 摘要周期之外执行,因此视图未更新。要么在scope.ShowFailedMessage = false;后添加scope.$apply(),要么使用$timeout服务而不是 setTimeout。第二种方法更好。

在此处查看$timeout服务文档:$timeout