2011-09-22 68 views
0

我正在嘗試使用javascript製作簡單的隱藏對象遊戲。當用戶找到並點擊圖像時,我想按以下順序發生3件事:聲音播放,圖像大小增加,圖像不可見。我遇到的問題是讓3個事件順序發生,而不是併發。現在看來,所有三個事件都發生在同一時間。使用JavaScript排序事件

我試過使用setTimeout(),雖然它確實創建了延遲,但它仍然在同一時間運行所有函數,即使每個函數都嵌套在setTimeout中。

實施例:(所有這樣做是等待則1.5秒播放的聲音並且使圖像看不見的):

function FindIt(image, id){ 
var t = setTimeout('sound()',10); 
var b = setTimeout('bigger(' + image + ')',30); 
var h = setTimeout('hide(' + image + ')',1500); 
} 

下面是我目前使用的功能和實際結果是:單擊圖像,沒有任何事情發生2秒,然後聲音播放,圖像不可見。

function FindIt(image, id){ 
sound(); 
bigger(image); 
hide(image); 
} 

function sound(){ 
document.getElementById("sound_element").innerHTML= "<embed src='chime.wav' hidden=true autostart=true loop=false>"; 
} 

function bigger(image){ 
var img = document.getElementById(image); 
img.style.width = 112; 
img.style.height = 112; 
} 


function hide(id){ 
var ms = 2000; 
ms += new Date().getTime(); 
while (new Date() < ms){} //Create a 2 second delay 
var img = document.getElementById(id); 
img.style.visibility='hidden'; 
} 

任何指導,將不勝感激!

+1

'while(new Date() katspaugh

回答

0

爲什麼不使用「事件」方式。像onTaskDone();

function task1(arg, onTask1Done){ 
    console.log(arg); 
    if(onTask1Done)onTask1Done(); 
} 

task1("working", function(){console.log("task2");}); 
3

按順序觸發的事情,你需要第一個完成後執行第二項一定時間,之後第二個完成執行第三項一定時間,等等

只有你的聲音()函數實際上需要一些時間,所以我建議如下:

function FindIt(image, id){ 
    sound(); 
    // set timer to start next action a certain time after the sound starts 
    setTimeout(function() { 
     bigger(image); 
     // set timer to start next action a certain time after making the image bigger 
     setTimeout (function() { 
      hide(image); 
     }, 1000); // set this time for how long you want to wait after bigger, before hide 
    }, 1000); // set the time here for how long you want to wait after starting the sound before making it bigger 
} 

僅供參考,以如jQuery或YUI庫中的動畫功能讓這樣的事情容易得多。

另外,請不要使用這種結構在你的JS:

while (new Date() < ms){} 

這鎖定了瀏覽器對於延遲,是非常不友好的觀衆。使用setTimeout來創建延遲。

作爲參考,使用jQuery中的動畫庫,jQuery代碼來處理對象的點擊,然後在2秒內將其動畫化爲更大尺寸,延遲1秒,然後滑動消失如下:

$("#rect").click(function() { 
    $(this).animate({height: 200, width: 400}, 2000).delay(1000).slideUp(); 
}); 

jQuery管理動畫隊列並處理設置所有定時器,併爲您執行所有排序和動畫。這是很多,編程更容易,並給出了一個非常好的結果。

你可以看到它的工作,並在這裏玩:http://jsfiddle.net/kC4Mz/

+0

謝謝,這工作! 'while(new Date() Daniel

0

的Frame.js庫旨在很好地處理這樣的情況:

function FindIt(image, id){ 
    Frame(10, function(next) { sound();  next(); }); 
    Frame(30, function(next) { bigger(image); next(); }); 
    Frame(1500, function(next) { hide(image); next(); }); 
    Frame.start(); 
} 

Frame.js在使用標準超時提供了許多優勢,特別是如果你做了很多這樣的事情,這對於一場比賽,你可能是。

https://github.com/bishopZ/Frame.js