Search code examples
javascriptcallbackhigher-order-functions

Passing anonymous JS function as a callback


I'm trying to understand callbacks in JS. Here is the example I am working with at the moment:

getData('http://fakedomain1234.com/userlist', writeData);

document.getElementById('output').innerHTML += "show this before data ...";

function getData(dataURI, callback) {
    // Normally you would actually connect to a server here.
    // We're just going to simulate a 3-second delay.
    var timer = setTimeout(function () {
        var dataArray = [123, 456, 789, 012, 345, 678];
        callback(dataArray);
    }, 3000);
}

function writeData(myData) {
    document.getElementById('output').innerHTML += myData;
}

My question is: is it possible to pass an anonymous function to getData() instead of a function that is already defined? If so, how would you got about doing this?


Solution

  • Just like the function you passed to setTimeout

    getData('http://fakedomain1234.com/userlist', function(myData) {
      document.getElementById('output').innerHTML += myData;
    });