views:

39

answers:

2

How do I add some sort of call back so that I can run further code after render() has completed?

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

}
A: 
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');};
revaxarts
+1  A: 

have render take a function reference as a parameter.

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; 
    } 
}

You don't have to give render an anonymous function for the fn parameter- it can be any function name you have defined.

lincolnk
thanks for the help although it seems to fire the alert straight away, and then every frame until clearInterval. I need to just fire the alert once after //Do the stuff has finished
davivid
cool got it. just passed the fn on down to renderIt(), and moved if (typeof fn !== 'undefined'){ fn(); } down into the clearInterval section in renderIt(). It seems to work, hope thats the correct way!
davivid
that should be fine, happy it's working out for you. i'll update the example to reflect your changes.
lincolnk
great thank you!
davivid