How to wait for the 'end' of 'resize' event and only then perform an action?

后端 未结 24 1630
深忆病人
深忆病人 2020-11-22 09:39

So I currently use something like:

$(window).resize(function(){resizedw();});

But this gets called many times while resizing process goes o

24条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 10:05

    UPDATE!

    Better alternative also created by me is here: https://stackoverflow.com/a/23692008/2829600 (supports "delete functions")

    ORIGINAL POST:

    I wrote this simple function for handling delay in execution, useful inside jQuery .scroll() and .resize() So callback_f will run only once for specific id string.

    function delay_exec( id, wait_time, callback_f ){
    
        // IF WAIT TIME IS NOT ENTERED IN FUNCTION CALL,
        // SET IT TO DEFAULT VALUE: 0.5 SECOND
        if( typeof wait_time === "undefined" )
            wait_time = 500;
    
        // CREATE GLOBAL ARRAY(IF ITS NOT ALREADY CREATED)
        // WHERE WE STORE CURRENTLY RUNNING setTimeout() FUNCTION FOR THIS ID
        if( typeof window['delay_exec'] === "undefined" )
            window['delay_exec'] = [];
    
        // RESET CURRENTLY RUNNING setTimeout() FUNCTION FOR THIS ID,
        // SO IN THAT WAY WE ARE SURE THAT callback_f WILL RUN ONLY ONE TIME
        // ( ON LATEST CALL ON delay_exec FUNCTION WITH SAME ID  )
        if( typeof window['delay_exec'][id] !== "undefined" )
            clearTimeout( window['delay_exec'][id] );
    
        // SET NEW TIMEOUT AND EXECUTE callback_f WHEN wait_time EXPIRES,
        // BUT ONLY IF THERE ISNT ANY MORE FUTURE CALLS ( IN wait_time PERIOD )
        // TO delay_exec FUNCTION WITH SAME ID AS CURRENT ONE
        window['delay_exec'][id] = setTimeout( callback_f , wait_time );
    }
    
    
    // USAGE
    
    jQuery(window).resize(function() {
    
        delay_exec('test1', 1000, function(){
            console.log('1st call to delay "test1" successfully executed!');
        });
    
        delay_exec('test1', 1000, function(){
            console.log('2nd call to delay "test1" successfully executed!');
        });
    
        delay_exec('test1', 1000, function(){
            console.log('3rd call to delay "test1" successfully executed!');
        });
    
        delay_exec('test2', 1000, function(){
            console.log('1st call to delay "test2" successfully executed!');
        });
    
        delay_exec('test3', 1000, function(){
            console.log('1st call to delay "test3" successfully executed!');
        });
    
    });
    
    /* RESULT
    3rd call to delay "test1" successfully executed!
    1st call to delay "test2" successfully executed!
    1st call to delay "test3" successfully executed!
    */
    

提交回复
热议问题