2012-03-10 54 views
1

我正在使用函數在三個不同位置將文本寫入畫布3次,目前該函數是無參數的,但它使用的全局變量是在函數調用之間更改以指示計數,該計數用於確定輸出的文本。它可以接受一個參數,並用於一個本地而不是全局變量的循環。HTML5中的JavaScript - 需要多次睡眠()以顯示步驟

這三個文本字符串後輸出到,我想按順序顯示畫布...

然後我把它清除畫布上,並顯示了最終結果的另一個功能。

我希望所有這些都會隨着時間的推移而順序發生。

我試過了setTimeout()和setInterval(),並且也嘗試了一個響應者建議的pausecomp(ms)函數。沒有人給了我我想要的結果。

這裏是我在做什麼樣...

c=document.getElementById("canvas"); 
ctx=c.getContext("2d"); 

function whap(opt) 
{ 
    var comp=Math.floor(Math.random()*3)+1; // determines computer choice 
    ctx.fillStyle="#92B9CC"; 
    ctx.fillRect(0,0, c.width, c.height); 

    num = 1; 
    goCount(); 
    sleep(500); 
    num = 2; 
    goCount(); 
    sleep(500); 
    num = 3; 
    goCount(); 
    sleep(500); 

    drawChoice(choice, comp); 
} 

function goCount() 
{ 
    ctx.fillStyle="#340CF7"; 
    if(num == 1) 
    { 
     ctx.fillText("One...", 50, 100); 
    } 
    else if(num == 2) 
    { 
     ctx.fillText("Two...", 100, 150); 
    } 
    else if(num == 3) 
    { 
     ctx.fillText("Three...", 150, 200); 
    } 
    else 
    { 
     ctx.fillText("Go!!", 200, 250); 
    } 
} 

function drawChoice(n, x) 
{ 
    /* this function redraws the canvas the based on the two parameters, 
determines whether the player won or lost and fills the canvas 
with the results... drawing the appropriate images onto the canvas 
then filling the canvas with the appropriate text. 
    */ 
} 
+1

您可以製作一個擁有所有代碼的jsfiddle嗎? – rwilliams 2012-03-10 20:32:25

回答

2

一般來說,你不能阻止在JS調用(只有少數例外,但這些不推薦,因爲它會阻止整個UI )。因此,無論您需要使用延遲對象還是需要使用如下這樣的回調:

function sleep(next) { 
    window.setTimeout(next, 500); 
} 

num=1; 
goCount(); 

sleep(function() { 
    num = 2; 
    goCount(); 

    sleep(function() { 
     num = 3; 
     goCount(); 

     sleep(function() { 
      drawChoice(choice, comp); 
     }); 
    }); 
}); 
+0

謝謝d_inevitable ...我想我明白你已發佈的內容......除了一件事。你有每個num = value行後,你有一個countAndSleep(函數(){...}我有什麼功能()你放在哪裏?謝謝! – JanV 2012-03-10 20:55:53

+0

好吧,我已經編輯我的代碼,使更清楚。代碼從你的num = 1開始,到你有drawChoice(choice,comp)的地方結束。function(){...}是一個匿名函數,它是合法的語法。 – 2012-03-10 21:00:44