Using clearTimeout in mouseleave event [SOLVED]


#1

I want to use menu expandable by “mouseover” event.
But if mouse moves quickly over the menu element it shouldn’t expand. Let’s say desirable delay is 300 ms.

That’s how it looks in the template events.
“timer” is global variable

"mouseover .menu": (event, template) ->
	timer = setTimeout ->
		# menu expanded
		$(".menu").addClass 'menuOpened'
	, 300

"mouseleave .menu": (event, template) ->
	#clear timer on mouseleave event
	clearTimeout timer

But this solution doesn’t work as desired. Timer clear call in the mouseleave event doesn’t affect mouseover event and menu is opened after 300ms in any case.


#2

Caveat: I do not know CS. However, this looks like a variable scoping problem to me (timer in the mouseover event is not the same timer as in mouseleave).


#3

Try scoping the timeout to the template instance:

"mouseover .menu": (event, template) ->
	template.timer = setTimeout ->
		# menu expanded
		$(".menu").addClass 'menuOpened'
	, 300

"mouseleave .menu": (event, template) ->
	#clear timer on mouseleave event
	clearTimeout template.timer if template.timer?

#4

Thanks @coagmano!

Scoping variable to the template instance helped to solve the issue