设置For循环之间的延迟



我用jquery创建了这个函数,我想在每个循环之间设置一个延迟,我试图在for循环中设置Interval,但它不起作用。

$(document).ready(function() {
$(window).scroll( function(){
for(let i =1;i <=6 ;i++){
$('#steps_icon-'+i).each( function(){
var bottom_of_object = $(this).position().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
if( bottom_of_window > bottom_of_object ){
$(this).animate({'opacity':'1'
,'transform':'translateY(0px)',
},2000);
}
});
}
});
});

当你滚动这个功能时,它会显示一个图标,但我想设置每个图标之间的延迟。

您可以使用setTimeout使其等待。但是它是异步的,所以你应该使用异步等待关键字。

// Function to make program wait
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Your code
$(document).ready(function() {
$(window).scroll( async function(){ // Added async keyword here
for(let i =1;i <=6 ;i++){
await sleep(200) // Added this line
$('#steps_icon-'+i).each( function(){
var bottom_of_object = $(this).position().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
if( bottom_of_window > bottom_of_object ){
$(this).animate({'opacity':'1'
,'transform':'translateY(0px)',
},2000);
}
});
}
});
});
```

最新更新