Get variable and count from 0 - javascript

Forgive me if this sounds a little confusing ... I am trying to adjust the value of a progress bar based on my randomize variable.
var randomize = Math.round(Math.random() * (3000 - 2000) + 1000);
How do I then get javascript to count from 0 to 'randomize' in seconds, so that I can apply it to my progress bar?

You could do something like this:
var randomize = Math.round(Math.random() * (3000 - 2000) + 1000);
var counter = 0;
var timer = setInterval( function(){
if ( counter <= randomize ){
// update progress bar
counter += 1;
}else{
clearInterval( timer );
}
}, 1000 );
Basically what I'm doing here is setting up a function to be called every second ( 1000 = 1 second in JavaScript). The timer will check if the counter variable has reached the value of randomize and if not, it will increment it's value by one.
Once counter is equal to randomize, the timer will be cleared.
References -
setInterval()
clearInterval()

var seconds = 0;
var timer = setInterval(function() {
seconds = seconds + 1;
if (seconds == randomize) {
clearInterval(timer);
}
}, 1000);

Related

How to get seconds to countdown properly after button click event

To start, I am brand new to Javascript so please excuse my naivete.
I am working on a countdown timer to start on a button click. The timer does start on the click, however, the seconds timer immediately changes (minus 1) and then after that proceeds to countdown every second (as desired).
for example: timer is at 25:00.
button is clicked, timer immediately drops to 24:59 (without a second passing)
then proceeds to countdown as normal.
Thank you in advance.
let min = 25;
let sec = 60;
let remainSec = sec % 1;
let minText = document.getElementById('minutes');
minText.innerText = min; //declared outside of sample
let secondsText = document.getElementById('seconds');
secondsText.innerText = remainSec + '0' ; //declared outside of sample
startTime.addEventListener('click', decrement); //declared outside of sample
function decrement() {
sec--;
secondsText.innerText = sec;
if (sec < 10){
secondsText.innerText = '0' + sec;
}
setInterval(decrement, 1000);
}
You can use a timeout:
startTime.addEventListener('click', function() { setTimeout(decrement,1000) });
You don't need the setInterval inside the decrement function, this way it will be called multiple times, and the decrement will occur more then once per second.
Do something like this:
startTime.addEventListener('click', decrement); //declared outside of sample
let interval;
function startDecrement() {
if (!interval) { // avoid duplicate interval
interval = setInterval(decrement, 1000);
}
}
function decrement() {
sec--;
secondsText.innerText = sec;
if (sec < 10){
secondsText.innerText = '0' + sec;
}
}
Another cool stuff is that storing the interval allows you cancelling it using the [clearInterval()](
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval) function.
function stopDecrement() {
clearInterval(interval);
interval = null;
}
Additional information
The if statement that checks if a interval was already declared works because javascript any value in a Truthy or Falsy value when using with ! (NOT operator). See Understanding JavaScript Truthy and Falsy
So, when you call setInterval() it returns an unique non-zero integer that identifies the interval, allowing you to cancel it in the future.
On the first run, the interval variable is empty because we just declared it without a value.
let interval;
console.log(interval); // undefined
console.log(!interval); // true
interval = setInterval(decrement, 1000);
console.log(interval); // 1
console.log(!interval); // false

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);
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>

Timer counting faster on second run

I am working on a simple game right now. its almost done except for the timer has a glitch in it and I can't figure out whats doing it. when you push a button, an HTML5 text on the canvas starts to count down from 35 to 0. On the first run it's fine. But if you choose to play again with out refresh the timer starts to countdown faster. here is the code.
var timer = 35;
ctx.fillText("Countdown: " + timer, 320, 32);
function resetReggie(){
reggie.x = canvasWidth / 2;
reggie.y = canvasHeight / 2;
}
//Starts Timer for Timed Game
function timedMsg()
{
resetReggie();
ballsCaught = 0;
timer = 35;
alert('Pick up as many as you can in ' + timer + ' seconds');
countDown();
var t=setTimeout(function() {
var again = confirm("TIMES UP! You Gathered " + ballsCaught + " Balls! Play Again?");
if (again === true){
timedMsg();
resetReggie();
}
if (again === false){
resetReggie();
ballsCaught = 0;
timer = 35;
}
}, timer * 1000);
}
function countDown() {
if (timer != 0){
timer-=1;
setTimeout('countDown()', 1000);
}
}
I think the problem is in the line
}, timer * 1000);
where you have a value that is at most 34 at the time 'timer' is evaluated to set the timeout. Because you initialize it to 35 but then call countDown() which decreases it to 34, then you have a call to confirm() which might let 'timer' decrease even more. As a result the subsequent call to timedMsg() happens a little too soon causing countDown() to be called twice as often. Try the following (I ran it in node) and then change the 4 to 6.
function countDown() {
console.log("Countdown: " + timer, 320, 32);
if (timer != 0) {
timer -= 1;
setTimeout(countDown, 1000);
}
}
function timedMsg() {
timer = 5;
countDown();
var t=setTimeout(function() {
timedMsg();
}, 4 * 1000);
}
timedMsg();
As mentioned in my comment, each time you start a new game, it appears you are decreasing the timeout value. As a result, this reduces the time each time.
Try this:
var timeout = currentTime = 5;
var int = setInterval(function() {
​console.log(currentTime);
currentTime--;
if(currentTime < 0) {
var again = confirm('Play again?');
if(again) {
currentTime = timeout;
}
else {
clearInterval(int);
}
}
}, 1000);​
http://jsfiddle.net/gRoberts/CsyYx/
Look at your console (F12 in Chrome), or update the code to write to the browser to see it working ;)

Increment integer by 1; every 1 second

My aim is to create identify a piece of code that increments a number by 1, every 1 second:
We shall call our base number indexVariable, I then want to: indexVariable = indexVariable + 1 every 1 second; until my indexVariable has reached 360 - then I wish it to reset to 1 and carry out the loop again.
How would this be possible in Javascript? - if it makes a difference I am using the Raphael framework.
I have carried out research of JavaScript timing events and the Raphael delay function - but these do not seem to be the answer - can anyone assist?
You can use setInterval() for that reason.
var i = 1;
var interval = setInterval( increment, 1000);
function increment(){
i = i % 360 + 1;
}
edit: the code for your your followup-question:
var interval = setInterval( rotate, 1000);
function rotate(){
percentArrow.rotate(1,150,150);
}
I'm not entirely sure, how your rotate works, but you may have to store the degrees in a var and increment those var too like in the example above.
var indexVariable = 0;
setInterval(function () {
indexVariable = ++indexVariable % 360 + 1; // SET { 1-360 }
}, 1000);
Try:
var indexVariable = 0;
setInterval(
function () {
indexVariable = (indexVariable + 1) % 361;
}, 1000}

JavaScript countdown in random increments

i have spend an hour trying to find such a script to no avail
I want a simple countdown that starts at 200 units and decreases by a random increment between 0-3 units every second
var count = 200;
var timer = setInterval(function() {
count -= Math.floor(Math.random()*3);
if( count <= 0) {
count = 0;
clearInterval(timer);
}
},1000);

Categories

Resources