Javascript 停止 $timeout - AngularJS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27874310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:50:00  来源:igfitidea点击:

Stopping the $timeout - AngularJS

javascriptangularjs

提问by user2991183

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);


  };

});

When I mouseover a button, a pop up dialog box is show. When I mouseout, the pop up dialog box is going to be hidden in two seconds. The problem come when I mouseover the button for the second time. Even my cursor is still on the button, the pop up dialog box is hide in two second. How to stop the timer when the mouse is over the button again?

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

回答by ryeballar

The $timeoutservice returns a promise that can be cancelled using $timeout.cancel(). In your case, you have to cancel the timeout in every button mouse over.

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

DEMO

演示

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);
  };

});