2017-08-23 41 views
0

我只是在一個JavaScript課程的中間,我正在玩一個非常基礎的項目,我需要隨機出現隨機形狀(只是正方形和圓形)在頁面上的位置。一旦開始按鈕被點擊,第一個形狀需要在隨機延遲後出現。setTimeOut導致函數觸發按鈕被點擊前

本來我是在畫布上繪製形狀,但是隨後繪製的形狀需要稍後才能點擊,因爲我只需要生成正方形和圓形,我只使用形狀各異的div,大小和位置。點擊按鈕後,我的形狀顯得很好,但我正努力在功能上添加延遲。這是我的代碼,而無需延遲:

<button id="start">Start</button> 
    <div id="shape"></div> 

    <script type="text/javascript"> 

    function generateRandomShape() { 
     var randomColor = ["red", "green", "blue", "orange", "purple"]; 
     var radiusOptions = ["50%", ""] 
     document.getElementById("shape").style.backgroundColor = randomColor[Math.floor(Math.random() * randomColor.length)]; 
     document.getElementById("shape").style.borderRadius = radiusOptions[Math.floor(Math.random() * radiusOptions.length)]; 
     document.getElementById("shape").style.height = Math.random() * 500; 
     document.getElementById("shape").style.width = document.getElementById("shape").style.height; 
     document.getElementById("shape").style.marginLeft = Math.random() * 1000; 
     document.getElementById("shape").style.marginTop = Math.random() * 400; 
    }; 

    document.getElementById("start").onclick = generateRandomShape; 

    </script> 

我試圖修改的onclick電話如下:

 document.getElementById("start").onclick = setTimeOut(generateRandomShape,2000); 

但現在沒有被點擊的按鈕後2秒的函數觸發(我將加入在隨機元素延時使用Math.random一旦我得到這個工作!)。無法理解爲什麼這是在事件處理程序之前觸發的邏輯。

回答

1

這條線:

document.getElementById("start").onclick = setTimeOut(generateRandomShape,2000); 

導致setTimout功能,因爲一旦它遇到,執行功能和返回值(如果有的話)是什麼被分配到onclick財產立即運行。

行更改爲:

document.getElementById("start").onclick = function(){setTimeout(generateRandomShape,2000)}; 

,使得包含setTimeout指令的功能被存儲在onclick財產,不會運行,直到click事件發生。此外,您的大寫錯誤setTimeoutsetTimeOut

此外,您的script標籤中不需要type=text/javascript

除此之外,你的函數沒有寫得很好。您應該只掃描元素一個時間,而不是在你的代碼的每一行,像這樣:

function generateRandomShape() { 
 

 
    var randomColor = ["red", "green", "blue", "orange", "purple"]; 
 
    var radiusOptions = ["50%", ""] 
 
    var shape = document.getElementById("shape"); // <-- Just scan for the element once 
 
    
 
    shape.style.backgroundColor = randomColor[Math.floor(Math.random() * randomColor.length)]; 
 
    shape.style.borderRadius = radiusOptions[Math.floor(Math.random() * radiusOptions.length)]; 
 
    shape.style.height = Math.random() * 500; 
 
    shape.style.width = shape.style.height; 
 
    shape.style.marginLeft = Math.random() * 1000; 
 
    shape.style.marginTop = Math.random() * 400; 
 
}; 
 

 
// It's better to use modern standards for event wiring (.addEventListener) 
 
// instead of event properties (.onclick) 
 
document.getElementById("start").addEventListener("click",function(){ 
 
    // You had mis-capitalized setTimeout as setTimeOut! 
 
    setTimeout(generateRandomShape,2000) 
 
});
<button id="start">Start</button> 
 
<div id="shape">This is the shape element.</div>

+0

真棒這是真正有用的和超清晰。非常感謝你的幫助! – DaveB1