JavaScript Callback Pattern - Fibonacci

by LeeMellinger

HTML

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Callback Pattern</title>
</head>
<body>
    <header>
        <h1>JavaScript Callback Pattern</h1>
     </header>
    <article>
        <input id="serie" type="number" value="30" />
        <button id="btnGetSerie">Get Serie</button>
        <ul id="log"></ul>
    </article>
</body>
</html>

CSS

body {
    font-family: "Verdana";
    font-size: 9pt;
}

header {
    padding: 15px;
    box-shadow: 0px 1px 2px rgba(0,0,0,0.4);
    background-color: rgb(27, 161, 226);
    color: #fff;
}

    header h1 {
        font-size: 14pt;
    }


article {
    width: 80%;
    margin: auto;
    margin-top: 20px;
}

button{
    padding: 15px;    
}

JavaScript

function calculateFibonacci(number) {

    if (number == 0 || number == 1) return number;

    return (calculateFibonacci(number - 1) + calculateFibonacci(number - 2));
}

function doStuff(serie, successCallback, errorCallback) {

    try {
        var results = [];

        for (var i = 0; i < serie - 1; i++) {

            var result = calculateFibonacci(i);
            console.log(result);
            results.push(result);
        }

        console.log("for finished");

        if (typeof successCallback === "function") {
            successCallback(results.join(","));
        }

    }
    catch (ex) {
        if (typeof errorCallback === "function") {
            errorCallback(ex.message);
        }
    }
}

function output(log, msg) {
    log.innerHTML += "<li>" + msg + "</li>";

}

window.onload = function() {

    var log = document.getElementById("log");
    var btnGetSerie = document.getElementById("btnGetSerie");

    btnGetSerie.addEventListener("click", function() {
        output(log, "Initialization");

        var value = document.getElementById("serie").value;

        doStuff(value,

        function(result) {
            output(log, "This is your result: " + result);
        }, function(error) {

            output(log, "Something bad happened: " + error);
        });

        output(log, "doStuff has already called");
    });
    
    output(log, 'last call!');
};