JS添加回调以运行下一个函数?

时间:2010-09-29 15:31:59

标签: javascript design-patterns function callback

如何添加某种回调以便在render()完成后运行更多代码?

function next(){
    target = max;
    render();

    //When render complete, do some more
    //change values....
    //render();

}

function prev(){
    target = min;
    render();

    //When render complete, do some more
}

var timer;

function render(){
    timer = setInterval(renderIt, 40);
}

function renderIt(){

    if (condition) {
    clearInterval(timer);
    return;
        }

    //Do the stuff

}

2 个答案:

答案 0 :(得分:1)

function next(callback){
    target = max;
    render(callback);

    //When render complete, do some more
    //change values....
    //render();

}
function render(callback){
    timer = setInterval(renderIt, 40);
    callback();
}

next(function(){alert('this is a callback');};

答案 1 :(得分:1)

render将函数引用作为参数。

function next(){ 
    target = max; 

    // pass a function reference to render
    render( function() { 
        //When render complete, do some more 
        //change values.... 
        alert('moved next!'); 
    } ); 

} 

function prev(){ 
    target = min; 
    render( function() { 
        //When render complete, do some more 
        alert('moved prev!');      
    } ); 

} 

var timer; 

function render(fn){ 
    // create an anonymous function to wrap your original call
    timer = setInterval(function() { 
                           // can't pass fn along to renderIt if undefined
                           if (typeof fn === 'undefined') { fn = null; }
                           renderIt(fn); 
                       }, 40); 
} 

function renderIt(fn){ 

    if (condition) { 
        clearInterval(timer); 

       //Do the stuff 
        if (typeof fn === 'function') {
            // invoke the passed method 
            fn();        
        }
        return; 
    } 
}

您不必为render参数提供fn匿名函数 - 它可以是您定义的任何函数名称。