Passing an anonymous function as a parameter in javascript

I have the following javascript code:

EventsManager.prototype.hideContainer = function() { var that = this; var index = that.getNextUnreadEventIndex(); if(index !== -1) { EventsManager.animateHideLeft(function() //<--- passing a function as parameter to another function { var unreadEvent = that.eventsList.splice(index,1)[0]; unreadEvent.isEventOnFocus = true; that.eventsList.push(unreadEvent); that.displayLastEvent(); }); } } 

Here is the code for the EventsManager.animateHideLeft () function:

 EventsManager.animateHideLeft = function(callback) { var p = document.getElementById("eventsContainer"); var width = parseFloat(p.style.width); if(!width || width === "NaN") width = 200; if(width <= 10) { clearTimeout(fr); alert(typeof callback); //<-- this shows "undefined" callback(); } else { width = width - 10; p.style.width = width + "px"; fr = setTimeout(function() { EventsManager.animateHideLeft(); }, 50); } }; 

Unfortunately, the animateHideLeft function is not working properly. When I check the callback type, it warns "undefined".

How can I fix this mess to get the expected result?

+4
source share
4 answers

It looks like you just need to pass the callback through the call to setTimeout .

 fr = setTimeout(function() { EventsManager.animateHideLeft(callback); }, 50); 
+5
source

You do not need a callback elsewhere

  fr = setTimeout(function() { EventsManager.animateHideLeft(function(){ //// }); }, 50); 
+3
source

This is because you will incorrectly name it with setTimeout() :

 EventsManager.animateHideLeft(); // No callback! 
+3
source

In setTimeout you do not pass a callback to the following call:

  EventsManager.animateHideLeft(); 

Change it to

  EventsManager.animateHideLeft(callback); 

However, it would be nice to test against typeof callback == "function" , because sometimes you do not need / need a callback function, but call callback(); will result in an exception.

Btw, you do not need clearTimeout(fr); (if you do not plan to call the function several times during the animation).

+3
source

All Articles