JSのasync/awaitを使ってフェードアニメーション完了後にログにOKと出す処理を書いたいのですが、
アニメーションが動いてる最中にOKと出力されてしまいます。
下記の修正すべき点をご指摘いただけませんでしょうか。
<script> jQuery( function($){ $(".home .s3 .box").css("position","absolute"); $(window).on("load scroll resize", function(){ asyncFunction(); }); function promiseIncrement() { return new Promise((resolve) => { $(".as").each(function(i){ var imgPos = $(this).offset().top; var scroll = $(window).scrollTop(); var windowHeight = $(window).height(); if (scroll > imgPos - windowHeight + windowHeight / 3){ // ここに処理を書く $(this).delay(200).css("visibility","visible").animate({opacity: 1}, 1000); } console.log(i); }); resolve(); //処理が完了したことを通知 }); } async function asyncFunction(x) { // await で Promise の解決を待つ const n = await promiseIncrement(); console.log('OK'); $(".home .s3 .box").css('position', 'relative'); } }); </script>
編集
下記のコードで期待する動作となりました。
$(".home .s3 .box").css("position","absolute"); $(window).on("load scroll resize", function(){ promiseIncrement(); }); function promiseIncrement() { var deferredArr = []; $(".as").each(function(i){ var imgPos = $(this).offset().top; var scroll = $(window).scrollTop(); var windowHeight = $(window).height(); if (scroll > imgPos - windowHeight + windowHeight / 3){ // ここに処理を書く deferredArr.push( $(this).delay(200*i).css("visibility","visible").animate({opacity: 1}, 1000)); } }); if( deferredArr.length > 0 ){ $.when.apply( $,deferredArr ).done(function(){ console.log('OK'); }); } } ```
回答2件
あなたの回答
tips
プレビュー