如果计时事件,则拼接结果



我希望能够取出定时事件的结果,但我不确定如何找到它的索引。问题是我按时间而不是索引号从数组中选择一个项目,所以我需要能够在计时器运行后获得结果。

它将沿着

mixedgroup1.splice(i, 1);

其中 i 是最终结果的索引号,但我无法知道如何获得它。

有什么想法吗?

这是JS代码:

var basket = ['apple', 'banana', 'cherry', 'durian', 'eggplant', 'fig', 'grapes', 'huckleberry', 'kiwi', 'lemon', 'mango'];
 function randOrd(){
return (Math.round(Math.random())-0.5); } 
 mixedBasket = basket.sort( randOrd ); //randomize the array
 var i = 0;  // the index of the current item to show

 function showBasket(){
 fruitDisplay = setInterval(function() {            
    document
        .getElementById('fruit')
        .innerHTML = mixedBasket[i++];    // get the item and increment
    if (i == mixedBasket.length) i = 0;   // reset to first element if you've reached the end
 }, 70);  //speed to display items
 var endFruitDisplay = setTimeout(function( ) { clearInterval(fruitDisplay); }, 3600); 
 //stop display after x milliseconds
}

这是 HTML:

<html>
<head></head>
<body>

<center>
   <h1> <span id="fruit"></span><p></h1>
 <script> var fruitSound = new Audio(); 
        fruitSound.src = "boardfill.mp3"; 
    function showFruitwithSound()
    { 
    fruitSound.play(); // Play button sound now 
    showBasket()
    } 
 </script>
<button onclick="showFruitwithSound()">Choose Fruit</button>
</center> 
<script type="text/javascript" src="Fruitpicker3.js"></script>
</body>
</html>

以下是获取最终结果索引的方法:

mixedBasket.indexOf(document.getElementById('fruit').innerHTML);

在此处添加以下内容:

var endFruitDisplay = setTimeout(function( ) { 
        clearInterval(fruitDisplay); 
        var index = mixedBasket.indexOf(document.getElementById('fruit').innerHTML); 
        //do splice and stuff
        document.getElementById("indexnum").innerHTML = index;    
    }, 3600); 

很抱歉这么密集,但我对 js 相当陌生。我根本无法从中获得任何输出。这是重写:

 <center>
 <h1> <span id="fruit"></span><p></h1> 
   <script> var fruitSound = new Audio(); 
    fruitSound.src = "boardfill.mp3"; 
    function showFruitwithSound()
    { 
    fruitSound.play(); // Play button sound now 
    showBasket()
    } 
 </script>
 <p id = "indexnum">
 <button onclick="showFruitwithSound()">Choose Fruit</button>
   </center> 
 <script>  
 var indexf = mixedBasket.indexOf(document.getElementById('fruit').innerHTML);
 document.getElementById("indexnum").innerHTML = indexf + " this is the index number."; 
 </script>
  <script type="text/javascript" src="Fruitpicker3.js"></script>
 </body>

最新更新