2
function lemath()
{
    var count;
    count = 0;
    stuff.innerHTML = "stuff" + count;

}

function begin()
{
    lemath();
    setTimeout(function() {
        begin();
    }, 1000);

}

I'm trying to create an infinite loop that will count each time it loops and display it, but when I do the code above it just gives back undefined? Thank you very much with the help! :)

2
  • 1
    Where is stuff defined ? count appear to be reset to 0 at each call to lemath ? Commented Nov 26, 2015 at 17:22
  • stuff is just the name of the header. Commented Nov 26, 2015 at 17:28

2 Answers 2

1
var count = 0; // declaring "count" here makes the variable globally available

function lemath()
{    
    count++;
    var stuff = document.getElementById('stuff');
    stuff.innerHTML = "stuff: " + count;
}

function begin()
{
    lemath();
    setTimeout(begin, 1000, window);
}

document.addEventListener('DOMContentLoaded', function () {    
    begin();
});

Demo: http://jsfiddle.net/pottersky/jj30s2Le/1/

Sign up to request clarification or add additional context in comments.

1 Comment

Oh my god thank you, I've been struggling with this for past 3 hours!
0

you can use setInterval javascript method for increase your counter


// setInterval(fn, time);

 // your counter state should be start from 0
let count = 0;

// Your function should be run each time (for example each second)
const increment = () => {
    count++
// show count in console or in DOM
    console.log(count)
    element.innerHTML = count
}

setInterval(increment, 1000);


For Performance reason and for stop or reset timer you can use clearInterval method


const timer = setInterval(increment, 1000);

 // stop counter

  clearInterval(timer)


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.