LFJ__ LFJ__ - 2 months ago 13
Javascript Question

Javascipt time-based score in Firefox

So i've got this problem,

For a score function I have that increases by one per second, it works in Google Chrome (version 53.0.2785.116 m), Microsoft Edge (25.10586.0.0) however does not work in Firefox (version 49.0.1). Is this likely due to the differences in date format?

The code below is my time-based score of a canvas game. The function obtains the date from the start of execution, and increases by 1 for each second.

It is key that the score starts from 0, increases by 1 per sec, and reaches 100 in the browser.




Looking for any solution that will make this work on Firefox - at the moment the 'score' appears static and does not count upwards, unlike Google Chrome and Edge.

Any ideas? - New to JS.
Thanks in advance for your help.



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

var interval = window.setInterval(function() {
var time = new Date().getTime() - start;

score = Math.floor(time / 1000);

if(score === 100) {
window.clearInterval(interval);
if(!alert("You win!\nPress 'OK' to play again")){
window.location.reload();
}
}

document.getElementById('displayScore').innerHTML = score += '.00 Score';
});

<div id="displayScore"></div>




Answer

You need to pass the delay in your setIntetval because if you don't firefox assumes a default of 10 (millisec)

delay The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. If this parameter is less than 10, a value of 10 is used.

This makes it run every 10ms its a very low value so when you do the calculation like score = Math.floor(time / 1000); resulting value nears to zero and your var never increments

Comments