Question

Currently programming Hangman and I have the following problem:

When I create a new HangmanController (choosing a new word, ...) the timer works fine, the only thing is, when I create one more HangmanController, the speed is 2x faster, when I create one more HangmanController 3x, etc. I create a HangmanController only when

Where's the problem? Or how can I make the timer better?

//Here's where I create a new HangmanController. This happens when the user changes the difficulty (pressing a button in the HTML)

function inithm(difficulty) {
    hm = new HangmanController();
    hm.hmModel.reset(hm.displayedWord.word, false, difficulty);
    UsedLetters();
};

//Constructor

HangmanController = function() {
    this.hmModel = new HangmanModel();
    //this.hmView = new HangmanView(document.getElementById('hm_view'));
    this.displayedWord = new DisplayedWord();
    this.userGuessField = document.getElementById('guessfield');
    this.userGuessField.focus();
    this.guessbutton = document.getElementById('guessbutton');
    this.guessbutton.disabled = false;
    /*this.updateTime = function(stopwatch) {
        var e = stopwatch.getElapsed();
        document.getElementById('stopwatch').innerHTML = e.hours * 60 + e.minutes + ' mins' + e.seconds + ' secs';
    };*/
    this.stopwatch = new Stopwatch();
};

//Timer, it is only called here, nowhere else (at setInterval)

Stopwatch = function() {
    this.sek = 0;
    setInterval(function() {timer();}, 1000);
};

function timer() {
    document.getElementById('stopwatch').innerHTML = this.hm.stopwatch.sek;
        this.hm.stopwatch.sek++;
}

Stopwatch.prototype.stop = function() {
    document.getElementById('stopwatch').innerHTML = 0;
};
Was it helpful?

Solution

You are creating several instances of Stopwatch with each HangmanController, and everyone of them is calling timer() every second, which results in your #stopwatch element beeing increased more often than just once a second ;-)

edit: You should either dispose of the old HangmanController (especially the Stopwatch functionality) before creating a new one, or instead only create one instance of HangmanController, and make a method for restarting, or difficulty changes, etc..

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