我使用函数在三个不同的地方将文本写入画布3次,目前该函数是无参数的,但它使用在函数调用之间更改的全局变量来指示计数,这用于确定输出的文本。它可以采用一个参数,并在具有局部变量而不是全局变量的循环中使用。
将这三个文本字符串输出到画布后我想依次显示...
然后我调用另一个清除画布并显示最终结果的函数。
我希望所有这些都按时间顺序发生。
我尝试了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.
*/
}
答案 0 :(得分: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);
});
});
});