Stopping the $timeout - AngularJS

Stopping the $timeout - AngularJS

本文关键字:AngularJS timeout the Stopping      更新时间:2023-09-26
var app = angular.module('myapp', []);
app.controller('PopupCtrl', function($scope, $timeout){
$scope.show = 'none';

  $scope.mouseover = function(){
    console.log('Mouse Enter');
    $scope.show = 'block';
  };
  $scope.mouseout = function(){
       console.log('Mouse Leave');
        var timer = $timeout(function () {
          $scope.show = 'none';
        }, 2000);

  };
});

当我将鼠标悬停在按钮上时,会显示一个弹出对话框。当我鼠标退出时,弹出的对话框将在两秒钟内隐藏。当我第二次将鼠标悬停在按钮上时,问题就来了。即使我的光标仍然在按钮上,弹出对话框也在两秒钟内隐藏。当鼠标再次悬停在按钮上时如何停止计时器?

$timeout 服务返回一个承诺,可以使用 $timeout.cancel() 取消该承诺。在您的情况下,您必须取消每个按钮鼠标的超时。

演示

JAVASCRIPT

var app = angular.module('myapp', []);
app.controller('PopupCtrl', function($scope, $timeout){
  var timer;
  $scope.show = false;
  $scope.mouseover = function(){
    $timeout.cancel(timer);
    $scope.show = true;
  };
  $scope.mouseout = function(){
    timer = $timeout(function () {
      $scope.show = false;
    }, 2000);
  };
});