سؤال

I would like to change a number from n1 to n2 gradually that is if n1 is 5 & n2 is 10 then I want it to change like 6, 7, 8, 9, 10 instead of changing abruptly from 5 to 10

Here is the part;

var interval = setInterval(gMoneyU1, 1000);
function gMoneyU1()
{
    var calc = 5 * U1Amount;
    Money += calc;
    document.getElementById('money').innerHTML=Money + "$";
}
هل كانت مفيدة؟

المحلول

I think you should use setTimeout to achieve this, I am writing a more general code but you can easily fit it to your case

var initial = 0;
var final = 5;

function change(current, expected){
    if(current != expected){
        setTimeout(function(){
            current += ((expected-current > 0) ? 1 : -1)); //increment or decrement based on the case
            change(current, expected);
        }, 1000);
    }
}

change(0, 5);

نصائح أخرى

Here you have:

var interval = setInterval(gMoneyU1, 1000);
var Money = 0, U1Amount = 1;  //Start U1Amount in 1
function gMoneyU1()
{
    var calc = 5 * U1Amount;
    Money += calc;
    U1Amount++;  //Increment amount by 1
    document.getElementById('money').innerHTML=Money + "$";
}

Cheers

Here is my understanding of this question :

var money = 5,
    ceiling = 10,
    el = document.getElementById('money'),
    tid = setInterval(update, 500);

function update() {
    refresh(++money);
    if (money === ceiling) clearInterval(tid);
}

function refresh(value) {
    el.innerHTML = value + '$';
}

refresh(money);

Have a look at the demo : http://jsfiddle.net/wared/4DmxG/.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top