Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping the $timeout - AngularJS

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?

like image 759
user2991183 Avatar asked Jan 10 '15 08:01

user2991183


People also ask

How do I stop setTimeout?

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.

How do you reset a $timeout and disable a watch ()?

var customTimeout = $timeout(function () { // arbitrary code }, 55); $timeout. cancel(customTimeout); The same applies to “$interval()”. To disable a watch, just call it.

What does $Timeout do in AngularJS?

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.

What is difference between timeout and setTimeout?

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.


1 Answers

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

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);   };  }); 
like image 140
ryeballar Avatar answered Sep 21 '22 18:09

ryeballar