Question

I am wondering how to make this if loop pause once every second before continuing to count the amount of "candy" I have.

Edit: I want to pause so that every second the amount of candy I have goes up by 1. Currently the display starts showing 1 through 10. I'm attempting to copy the effect done here (I'm very new to JavaScript): http://candies.aniwey.net/

//booleans
var count = new Boolean;
count = true;
//integers
var candy = 0;

//strings
var txt = "You have ";
var txt1 = " candies.";
var br = "<br>";


//loops
while (candy <= 10) {
    if (candy == 0) {
        document.write(txt + candy + txt1);
        document.write(br);
        candy++;
    } else if (candy == 1) {
        document.write(txt + candy + " candy.");
        document.write(br);
        candy++;
    } else {
        document.write(txt + candy + txt1);
        document.write(br);
        candy++;
    }
}
Was it helpful?

Solution

Instead of a loop, use window.setInterval():

var candy = 0;
window.setInterval(function() {
  document.write("You have " + ++candy + " candy.<br/>");
}, 1000);

OTHER TIPS

Use setTimeout to call a function (jsfiddle)

var candy = 0;
function moreCandy() {
    document.getElementById('textHere').innerHTML += 'You have ' + candy + 
        (candy == 1 ? ' candy' : ' candies') + '<br />';
    candy++;
    if (candy <= 10) {
        setTimeout(moreCandy, 1000);
    }
}
moreCandy();

or alternatively

for (var i = 0; i <= 10; i++) {
    setTimeout(getCandy(i), i * 1000);
}

function getCandy(amount) {
    return function () {
        document.getElementById('textHere').innerHTML += 
            'You have ' + amount + 
            (amount == 1 ? ' candy' : ' candies') + '<br />';
    };
}

JavaScript execution cannot be paused. You would need to refactor this code to call functions based on timers instead.

BTW - never never never use document.write. Use DOM methods, like .innerHTML.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top