jquery setTimeout或setInterval [英] jquery setTimeout or setInterval
问题描述
我有以下代码与if条件
I have the below code with the if condition
if(oldMembership++ <= newMembership) {
var digit;
$('ul#indexSiteCounterBottom').empty();
for(i = 0; i < 9; i++) {
if(membership.toString()[i] == '_') {
digit = ' ';
} else {
digit = membership.toString()[i];
}
$('ul#indexSiteCounterBottom').append('<li>'+digit+'</li>');
$('ul#indexSiteCounterBottom li:nth-child(3n)').addClass('extra-margin');
}
}
如果'if'条件满足其余代码运行。
If the 'if' condition is meet the rest of the code is run.
我想能够在'if'的每个循环中减慢下面的代码运行大约500ms。
I want to be able to slow the running of the below code by around 500ms for each loop of the 'if'.
我试图插入setInterval和setTimeout,但我没有使用它们,'if'条件立即完成所有循环。
I've tried to put in setInterval and setTimeout but I haven't used them before and the 'if' condition completed all loops instantly.
我如何添加setInterval或SetTimeout到这个每个if循环延迟500ms?一旦'if'条件满足,它应该退出定时器/如果条件。
How can I add setInterval or SetTimeout to this so each 'if' loop is delayed by 500ms? Once the 'if' condition is meet it should drop out of the timer/if condition.
非常感谢...
推荐答案
我认为这可以解决你的问题...
I think this can resolve your problem...
function execute_if_membership(){
setTimeout(function(){
var digit;
$('ul#indexSiteCounterBottom').empty();
for(i = 0; i < 9; i++) {
if(membership.toString()[i] == '_') {
digit = ' ';
} else {
digit = membership.toString()[i];
}
$('ul#indexSiteCounterBottom').append('<li>'+digit+'</li>');
$('ul#indexSiteCounterBottom li:nth-child(3n)').addClass('extra-margin');
}
// Execute again if needed
if(oldMembership++ <= newMembership) {execute_if_membership();}
else{ /* what to do else? maybe call another function */ }
},500);
}
// execute by the first time
if(oldMembership++ <= newMembership) {execute_if_membership();}
EDIT:第一次。函数等待500 ms并执行,在函数的最后,它检查是否需要调用另一个时间(循环),如果需要它再次执行。如果你想在那之后执行一些代码,你需要把它放在条件的ELSE里面,因为如果你把另一个代码放在下面,它会被执行而不必等待。这是因为 setTimeout
和 setInterval
使代码异步并继续执行代码。
With this code you call the function by the first time. Function wait 500 ms and execute, in the final of the function, it checks if need to call another time (loop) and if needed it executes again. If you want to execute some code after that, you need to put it inside the ELSE of condition, because if you put another code below, it will be executed without wait. That's because setTimeout
and setInterval
makes the code asynchronous and continues to execute the code.
这篇关于jquery setTimeout或setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!