停止switch方法内部的嵌套if循环使用Javascript

时间:2015-04-27 14:40:05

标签: javascript jquery arrays switch-statement

所以我的朋友和我在过去几天都在为应用程序工作,唯一的问题是我们都不懂JavaScript。它一直很顺利,直到这一点。我从谷歌搜索了一堆,但我似乎无法解决这个问题。所以我们有一个调用函数的下拉菜单,

select id="vg" class="dropdown" onchange="vgchosen.call(this, event)">

这将我们归结为我们的功能,名为vgchosen。在这个函数中,有一个切换方法可以帮助评估选择下拉菜单选项。

function vgchosen(event) {
alert(this.options[this.selectedIndex].text);
var vgc = document.getElementById("vg").selectedIndex;
var y = document.getElementById("vg").options;


switch (y[vgc].text) {
case "Action":
    var actionvgc = [
    "You should play |Skyrim",
    "You should play |Killing Floor 2",
    "You Should play |Counter Strike Global Offensive",
    "You should play |Left 4 Dead",
    "You should play |House of the Dead",
    "You should play |Elite: Dangerous",
    "You should play |Middle Earth: Shadow of Mordor",
    "You should play |Crypt of the Necro Dancer",
    "You should play |The Witcher 3: Wild Hunt",
    "You should play |Dark Souls",
    ];
    setInterval(function() {
        var i = Math.round((Math.random()) * actionvgc.length);
        if (i == actionvgc.length) --i;
        $("#actionvgc").html(actionvgc[i]);
        }, 1 * 1000);
        break;


case "Shooter":
    var shootervgc = [
    "You should play |Skyri",
    "You should play |Killing Floor ",
    "You Should play |Counter Strike Global Offensiv",
    "You should play |Left 4 Dea",
    "You should play |House of the Dea",
    "You should play |Elite: Dangerou",
    "You should play |Middle Earth: Shadow of Mordo",
    "You should play |Crypt of the Necro Dance",
    "You should play |The Witcher 3: Wild Hun",
    "You should play |Dark Soul",
    ];
    setInterval(function() {
        var i = Math.round((Math.random()) * shootervgc.length);
        if (i == shootervgc.length) --i;
        $("#actionvgc").html(shootervgc[i]);
    }, 1 * 1000);
    break;
}
}

当您使用选项选项启动该功能时,一切正常,您每秒都会获得一个新的游戏创意。当您想要切换到其他选项时,问题就出现了。如果您选择射击游戏(游戏差异在于所有最后的字母都缺失),它将同时显示两个游戏创意。如何在启动新循环时停止第一个循环?

编辑:#actionvgc是显示文本的位置。这可以在这里看到

<div id="actionvgc">"Hello World! im FLi!"</div>

1 个答案:

答案 0 :(得分:2)

setInterval()函数返回一个标识该特定计时器的值。您可以稍后使用clearInterval()来停止它。

var timerId; // should probably be global

// ...

clearInterval(timerId); // clear prev timer
timerId = setInterval(function() { /* ... */ }, 1000);