use*_*550 4 javascript function execution settimeout
我有这个功能运行几秒钟使用setTimeout
.单击按钮时会运行此功能.
function complete() {
var div = document.getElementById('log');
setTimeout(function(){ div.innerHTML = div.innerHTML + intro[Math.floor(Math.random() * intro.length)] + "<br>"; }, 500);
setTimeout(function(){ div.innerHTML = div.innerHTML + second[Math.floor(Math.random() * second.length)] + "<br>"; }, 2560);
setTimeout(function(){ div.innerHTML = div.innerHTML + third[Math.floor(Math.random() * third.length)] + "<br>"; }, 4860);
setTimeout(function(){ div.innerHTML = div.innerHTML + fourth[Math.floor(Math.random() * fourth.length)] + "<br>"; }, 7860);
setTimeout(function(){ div.innerHTML = div.innerHTML + fifth[Math.floor(Math.random() * fifth.length)] + "<br>"; }, 9640);
}
Run Code Online (Sandbox Code Playgroud)
但是,如果用户多次单击该按钮,则此功能也会开始多次执行.我试图通过使用下面的代码来防止这种情况发生,但是,它无法正常工作.
var running;
function complete() {
if (running == true) { alert('error'); }
running = true;
var div = document.getElementById('log');
setTimeout(function(){ div.innerHTML = div.innerHTML + intro[Math.floor(Math.random() * intro.length)] + "<br>"; }, 500);
setTimeout(function(){ div.innerHTML = div.innerHTML + second[Math.floor(Math.random() * second.length)] + "<br>"; }, 2560);
setTimeout(function(){ div.innerHTML = div.innerHTML + third[Math.floor(Math.random() * third.length)] + "<br>"; }, 4860);
setTimeout(function(){ div.innerHTML = div.innerHTML + fourth[Math.floor(Math.random() * fourth.length)] + "<br>"; }, 7860);
setTimeout(function(){ div.innerHTML = div.innerHTML + fifth[Math.floor(Math.random() * fifth.length)] + "<br>"; }, 9640);
running = false;
}
Run Code Online (Sandbox Code Playgroud)
我应该采取什么方法,或者如何修复我的代码以便它可以完成我想要做的事情?
你running = false;
应该在内部超时功能,因为超时将异步执行,running = false;
将在超时结束前执行
一个简单的例子就是
var running = false,
div = document.getElementById('response'),
limit = 5,
current = 0;
$('#trigger').click(function () {
if (running === true) {
alert('Error: The cycle was running. Aborting.');
running = false;
return false;
}
running = true;
var end = setInterval(function () {
if (current >= limit || running == false) {
running = false;
clearInterval(end);
}
div.innerHTML += 'Hello World<br />';
current++;
}, 500);
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14654 次 |
最近记录: |