回调函数定义:
A callback is a function that is passed as an argument to another function and is executed after its parent function has completed。
一个回调是一个函数被传递一个参数到另外一个函数,被执行在主函数完成后
node2:/var/www/html/js#cat h41.html
<script>
//定义主函数,回调函数作为参数
function A(callback) {
console.log(callback);
callback();
console.log('我是主函数');
console.log('aaaaaaaaaaa');
}
//定义回调函数
function B(){
setTimeout("console.log('我是回调函数')", 30000);//模仿耗时操作
}
//调用主函数,将函数B传进去
A(B);
</script>
上面的代码中,我们先定义了主函数和回调函数,然后再去调用主函数,将回调函数传进去。
定义主函数的时候,我们让代码先去执行callback()回调函数,但输出结果却是后输出回调函数的内容。这就说明了主函数不用等待回调函数执行完,可以接着执行自己的代码。所以一般回调函数都用在耗时操作上面。比如ajax请求,比如处理文件等。