2014-10-22 168 views
0

我用setTimeout來傳遞運動。還有一點(可能是任何時候)我想暫停一下。我看過在這裏寫過的其他人。但很難理解。 任何人都可以給我一些建議工作嗎?謝謝。javascript暫停功能

function start(){ 
a(); 
} 

function a(){ 
document.getElementById('a').style.display = 'block'; 
setTimeout(b,1000); 
} 
function b(){ 
document.getElementById('b').style.display = 'block'; 
setTimeout(c,1000); 
} 
function c(){ 
document.getElementById('c').style.display = 'block'; 
setTimeout(d,1000); 
} 
function d(){ 
document.getElementById('d').style.display = 'block'; 
setTimeout(e,1000); 
} 
function e(){ 
document.getElementById('e').style.display = 'block'; 
} 
+1

對於每個元素,您不需要單獨的函數,可以定義一個接受選擇器參數的函數。 – undefined 2014-10-22 10:52:39

+0

[JavaScript,setTimeout]可能的重複(http://stackoverflow.com/questions/10312963/javascript-settimeout) – 2014-10-22 10:55:31

+1

我不清楚你想要做什麼。請編輯並描述你想要的內容。 – 2014-10-22 11:04:10

回答

0

這樣的事情?

<script> 
var timer = null; 
var callback = null; 

function start() { 
    clearTimeout(timer); // prevent a previous timer from doubling the speed 
    // first time, see if callback is set 
    if(! callback) { 
    callback = a; 
    } 
    // last function. make it stop 
    if(callback === e) { 
    return; 
    } 
    callback(); 
} 
function pause() { 
    clearTimeout(timer); 
} 

function a() { 
    document.getElementById('a').style.display = 'block'; 
    timer = setTimeout(b, 1000); 
    callback = a; 
} 
function b() { 
    document.getElementById('b').style.display = 'block'; 
    timer = setTimeout(c, 1000); 
    callback = b; 
} 
function c() { 
    document.getElementById('c').style.display = 'block'; 
    timer = setTimeout(d, 1000); 
    callback = c; 
} 
function d() { 
    document.getElementById('d').style.display = 'block'; 
    timer = setTimeout(e, 1000); 
    callback = d; 
} 
function e() { 
    document.getElementById('e').style.display = 'block'; 
    callback = e; 
} 
</script> 
<style> 
#a, #b, #c, #d, #e { 
    display: none; 
    width: 100px; 
    height: 100px; 
} 
</style> 

<input type="button" value="start" onclick="start()"> 
<input type="button" value="pause" onclick="pause()"> 

<div id="my_box"> 
    <div id="a">A</div> 
    <div id="b">B</div> 
    <div id="c">C</div> 
    <div id="d">D</div> 
    <div id="e">E</div> 
</div>