I'm trying to understand callbacks in JS. Here is the example I'm 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?
Thanks in advanced!
Just like the function you passed to setTimeout
getData('http://fakedomain1234.com/userlist', function(myData) {
document.getElementById('output').innerHTML += myData;
});
Just like you said:
getData('http://fakedomain1234.com/userlist', function(data) {
// contents of anonymous function
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.