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?
Cancelling a setTimeout Here's how... With this id and the clearTimeout JavaScript function, you can cancel a setTimeout . If the setTimeout declaration has not been completed, the clearTimeout function will cancel it, and the callback function will not be executed anymore.
var customTimeout = $timeout(function () { // arbitrary code }, 55); $timeout. cancel(customTimeout); The same applies to “$interval()”. To disable a watch, just call it.
The '$timeout' service of AngularJS is functionally similar to the 'window. setTimeout' object of vanilla JavaScript. This service allows the developer to set some time delay before the execution of the function.
Angular $timeout is a wrapper written for window. setTimeout in form of a try catch block which throws exceptions via $exceptionHandler service. $timeout accepts the function to be delayed, delay time, a boolean to invoke $. apply and parameters to be passed to the function.
The $timeout
service returns a promise that can be cancelled using $timeout.cancel()
. In your case, you have to cancel the timeout in every button mouse over.
DEMO
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); }; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With