Okay this is a basic question but as someone who has never worked with callback function before (ANYWHERE) and after many failures to understand what's going on, I thought that maybe you can help me.
Let's consider the following example:
When the html loads, the function showtext reveals the, passed as parameter, text by letter (just a tiny and beautiful animation). When this function finish, when all the sentence is shown, I want to call another function showAuthor that reveals the author of the above post.
function showText(target, message, index, interval, callback) {
if (index < message.length) {
$(target).append(message[index++]);
setTimeout(function() { showText(target, message, index, interval); }, interval);
}
if (callback && typeof(callback) === "function") {
callback();
}
}
function showAuthor() {
var name = '<span>as posted by someone</span>';
$(name).hide().appendTo(".author").fadeIn(300);
}
$(function() {
showText("#aboutMeMsg", "Some VERY cool text here", 0, 100, showAuthor());
});
The problem
The problem with the above code is that the function showAuthor is executed the same time when the function showtext is starting. That means that the showAuthor is able to complete before showText is completed.
I think the problem is that I use the function showText is recursive, but I can't solve the problem.
Now why is this happening, I can't get it....
showAuthorfunction as a callback but it's return value as a parameter to theshowTextfunction. (probably as "undefined")showAuthorfunction toshowTextfunction which is probably"undefined"and in theshowTextfunction you check thecallbackparameter withif (callback && typeof(callback) === "function") {callback();}and it just evaluates to false. You should passshowAuthorfunction's definition as indicated in the given answers. I mean without the invoking parens.