回调函数

函数是对象,也就意味着函数可以当作参数传入另外一个函数中。给函数writeCode()传入一个函数参数introduceBugs(),在某个时刻writeCode()执行了(或调用了)introduceBugs(),在这种情况下,我们称introduceBugs()是一个“回调函数”,简称“回调”

 

碰撞事例

var lastTime = Date.now();
//速度
var box1Speed = 100;
var box2Speed = 150;

var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");
function collides(rectA,rectB){
return !( rectA.y + rectA.height < rectB.y ||
rectB.y + rectB.height < rectA.y ||
rectA.x + rectA.width < rectB.x ||
rectB.x + rectB.width < rectA.x
)
}
function widhtHeight(element){
return {
x: element.offsetLeft,
y: element.offsetHeight,

width: element.offsetWidth,
height: element.offsetHeight
}
}
function main(){
var now = Date.now();
var dt = (now - lastTime) / 1000;

var rectA = widhtHeight(box1);
var rectB = widhtHeight(box2);

var flag = collides(rectA,rectB);
if(flag){
alert("碰撞");
return;
}else{
box1.style.left = parseInt(box1.style.left) + box1Speed * dt + "px";
box2.style.left = parseInt(box2.style.left) - box2Speed * dt + "px";
}

lastTime = now;
setTimeout(main,1000/60);
}
main();

posted @ 2014-11-24 18:47  胡珍  阅读(115)  评论(0编辑  收藏  举报