Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jQuery.Deferredを使って非同期な繰り返し処理を行う
/**
* [begin, end)の範囲で非同期的な繰り返し処理を行う
*
* @param {Object} options ループの設定
* begin, end: 範囲指定
* inc: まとめて実行する量
* duration: ループごとに間をあける時間[ms]
*
* @return {jQuery.Deferred}
* progress: 非同期処理を行う部分
* progress_func( index, deferred )
* done: ループ正常終了時のコールバック設定
* fail: ループを途中で抜けたときのコールバック設定
*/
function async_loop( options ) {
var deferred = jQuery.Deferred( );
var index = options.begin;
function loop_func( ) {
var deferred_list = [];
for ( var i = 0; i < options.inc && index < options.end; ++i, ++index ) {
deferred_list.push( (function( ) {
var local = jQuery.Deferred( );
deferred.notify( index, local );
return local.promise( );
})( ) );
}
var deferred_when = jQuery.when.apply( null, deferred_list );
deferred_when.done( function( ) {
if ( index < options.end ) {
setTimeout( loop_func, options.duration );
} else {
deferred.resolve( );
}
} );
deferred_when.fail( function( ) {
deferred.reject( );
} );
}
setTimeout( loop_func, 0 );
return deferred;
}
(function( ) {
var deferred = async_loop( {
begin : 0,
end : 20,
inc : 5,
duration : 1000
} );
deferred.progress( function( index, deferred ) {
console.log( index, 'start' );
setTimeout( function( ) {
console.log( index, 'finish' );
deferred.resolve( );
}, 500 );
} );
deferred.always( function( ) {
console.log( 'finish' );
} );
})( );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.