LFJ__ LFJ__ - 2 months ago 17
Javascript Question

Javascript score target alert

New to JS, please be nice.

In creating a Javascript score for a browser canvas game, the code below increases by 1 for each second. For the variable score to equal 100, how would I go about this function displaying a window alert for when it reaches this value?

Attempts similar to if(score == 100), alert(score) have not worked for me.

Below code will not currently work in JSFiddle, output displays in browser tab.



var start = new Date().getTime(),
score = '0.1';

window.setInterval(function() {
var time = new Date().getTime() - start;
score = Math.floor(time / 1000) ;
if(Math.round(score) == score)
{ score += '.0 Score'; }
document.title = score;
}, 100);




Answer

You might want to clear the interval when you are done. Otherwise the interval continues on executing and very soon the score is no longer 100 (or whatever the upper limit will be)

Something along the lines of:

var start = new Date().getTime(),
  score = '0.1';

// get handle to interval function
var interval = window.setInterval(function() {
  var time = new Date().getTime() - start;
  
  score = Math.floor(time / 1000);
  console.log(score);
  
  if (score >= 5) { // set to 5 for speedier test/check
    score += '.0 Score';
    window.clearInterval(interval); // clear interval to stop checking 
    alert(score);
  }
  document.getElementById('title').innerHTML = score; // display it
  document.title = score;
}, 100);
<div id="title"></div>

Comments