我有以下代码和if条件
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'的每个循环,我希望能够将下面代码的运行速度减慢大约500ms。
我试图输入setInterval和setTimeout但我之前没有使用它们,'if'条件立即完成所有循环。
如何为此添加setInterval或SetTimeout,以便每个'if'循环延迟500ms?一旦'if'条件满足,它应该退出timer / if条件。
非常感谢...
答案 0 :(得分:3)
if(membership.toString()[i] == '_') {
digit = ' ';
setTimeout(function () {
digitThing(digit);
}, 500);
}
else {
digit = membership.toString()[i];
digitThing(digit);
}
function digitThing(digit) {
$('ul#indexSiteCounterBottom').append('<li>'+digit+'</li>');
$('ul#indexSiteCounterBottom li:nth-child(3n)').addClass('extra-margin');
}
答案 1 :(得分:1)
setTimeout
是用于延迟函数执行的函数
您可以像以下一样使用它:
var to = setTimeout(function() {
// Your code that will be executed after 500 ms
}, 500);
如果您想在500ms之前取消呼叫,可以使用to
var并呼叫clearTimout(to)
。这将取消时间,并且您的功能将在500ms后不再运行。
setInterval
与setTimeout
不同,因为它会在没有任何操作的情况下每500毫秒运行一次。它可以被视为一个调度程序。
您可以像以下一样使用它:
var iv = setInterval(function() {
// Your code that will be executed every 500ms
}, 500);
如果要停止预定流程,可以使用iv
var并调用clearInterval(iv)
。这将取消qscheduler。
在您的情况下,如果您想要保持每次通话,请使用setTimeout
。
例如,您可以编写如下内容:
// Launch the task if the main test is ok
if(oldMembership++ <= newMembership) {
// Empty your main UL
$('ul#indexSiteCounterBottom').empty();
// Run the first process without timeout
runProcess(0, 500);
}
// Run one process
function runProcess(i, ms)
{
// Stop the recursivity when the end of the string is reached
if (i >= membership.toString().length)
return;
// Set default value for the digit
var digit = membership.toString()[i];
// Override the digit if requiered
if(digit == '_')
digit = ' ';
// Finally process the digit
$('ul#indexSiteCounterBottom').append('<li>'+digit+'</li>');
$('ul#indexSiteCounterBottom li:nth-child(3n)').addClass('extra-margin');
// Run the next process in 500ms
setTimout(function() {
runProcess(i+1, ms);
}, ms);
}
答案 2 :(得分:1)
我认为这可以解决您的问题...
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();}
编辑:使用此代码,您可以在第一时间调用该函数。函数等待500毫秒并执行,在函数的最后,它检查是否需要调用另一个时间(循环),如果需要,它再次执行。如果你想在那之后执行一些代码,你需要将它放在条件的ELSE中,因为如果你在下面添加另一个代码,它将在没有等待的情况下执行。那是因为setTimeout
和setInterval
使代码异步并继续执行代码。