【jQuery】遅延実行 – 数秒後にイベントを発生させる
2015年8月6日queue()を使って遅延
遅延実行でdelayを使いたいけどaddClass()などだと遅延してくれない。
そんなときに下記のように設定するとちゃんと動いてくれる。
//一秒遅らせて実行
$('.js-text').delay(1000).queue(function(){
$(this).text("へんか!");
});
setTimeout()でも同じような事が出来る。
こちらの方が普通なかんじかも。
//一秒後に実行
setTimeout(function(){
$('.js-setTimeout').text("へんか!");
},1000);
実際の動き(queue setTimeout)
/* クリックしたら1秒後に変化します
----------------------------------------------- */
$(".js-text").on('click',function(){
//1秒後
$('.js-text').delay(1000).queue(function(){
$(this).text("へんか!");
});
});
Deferredを使ってアニメーションに順序を付ける
遅延とはちょっと違うけどDeferredを使った順序づけのアニメーションができるのでメモ
var $deferredAnim = $.Deferred( function( deferredAnim ){
//thenでファンクション名を繋げる
deferredAnim.then(anim_01)
.then(anim_02)
.then(anim_03)
.then(anim_04)
});
//実行
$deferredAnim.resolve();
function anim_01 (){
return $(".red").delay(1000).animate({
"top": "+100"
},1000);
}
function anim_02 (){
$(".red").text("途中や!");
$(".red").animate({
"left": "+100"
},1000)
}
function anim_03 (){
$(".red").text("もうちょっとや");
return $(".red").animate({
"top": "0",
"left": "200"
},1000)
}
function anim_04 (){
$(".red").text("ゴール屋で!");
}