更改var的速度值onClick?

时间:2014-02-11 03:37:36

标签: javascript button onclick increment var

当用户单击按钮时,它将更改var速度值。我怎样才能做到这一点?目前,它设置为1000毫秒// 1秒,如下所示:

var increment = setInterval(increment,1000); // gain 1 ever second // THIS IS WHAT I WANT TO CHANGE

我想在点击按钮时将1000更改为2000。我认为它叫增量值?我只知道它在1000毫秒的时间内设置它以获得数字的速度。

代码链接:

http://pastebin.com/UPaT9n3F

2 个答案:

答案 0 :(得分:0)

我将其更改为使用setTimeout。所以:

var increment = setInterval(increment,1000); // gain 1 ever second // THIS IS WHAT I WANT TO CHANGE
function increment(){
    Coal = Coal % 99999999999999999999 + CoalRate;
    totalCoal = totalCoal % 99999999999999999999 + CoalRate;
    document.getElementById("Coalcounter").innerHTML="Coal : " + Math.round(Coal);
    document.getElementById("CoalClickercost").innerHTML="Upgrade Coal Clicker : " + Math.round(CoalClickerPrice);
    document.getElementById("CoalRatecost").innerHTML="Upgrade Coal Rate : " + Math.round(CoalRatePrice);
}

会变成:

var interval = 1000
function increment(){
    Coal = Coal % 99999999999999999999 + CoalRate;
    totalCoal = totalCoal % 99999999999999999999 + CoalRate;
    document.getElementById("Coalcounter").innerHTML="Coal : " + Math.round(Coal);
    document.getElementById("CoalClickercost").innerHTML="Upgrade Coal Clicker : " + Math.round(CoalClickerPrice);
    document.getElementById("CoalRatecost").innerHTML="Upgrade Coal Rate : " + Math.round(CoalRatePrice);
    window.setTimeout(interval)
}
increment()

然后你的onclick变得像......一样简单。

<button onclick="swapInterval">Swap</button>

function swapInterval() {
    if(interval==1000) interval = 2000
    else interval = 1000
}

请注意,这不会改变当前循环(例如,如果你在2000年,你在500毫秒后按下按钮,你仍然需要等待另一个1500毫秒才能触发)。

答案 1 :(得分:0)

您可以清除间隔并再次创建

$('#element').click(function(){
     window.clearInterval(incrementID); //
     timing = timing + 1000; //this is if you plan to keep adding up.
     incrementID = setInterval(increment, timing);// if not you can always hardcode 2000
});

也:

var timing = 1000;
var incrementID = setInterval(increment,timing); // gain 1 ever second // THIS IS WHAT I WANT TO CHANGE
//you should change the varname so that you can use the handle to clear the already set interval