Game Timer (Start, Pause, Stop) - javascript

I have a timer that starts when the game starts.
I need to figure out how to stop the timer when the game is over and then return the value (time that has elapsed)
Here is the timer I have:
function gameTimer(status) {
$(".notes").text(status);
if (gameStart == true) {
gameStart = false; // so game will not repeat when image is clicked again to start game
var timer = setInterval(calltimer, 1000);
function calltimer() {
$(".timerInner").text(time);
if (status == true) {
time++;
}
}
}
}
Here is how I vision the functions working:
gameTimer(start); // start timer
gameTimer(pause); // pause timer in case user needs to step away
gameTimer(stop); // stop timer and return value
Any ideas on how I would get something like this implemented?
Thanks,

Maybe u want something like this:
var gameStart = false;
function gameTimer (status) {
switch (status) {
case "start":
if (gameStart === false) {
var timer = setInterval(callTimer, 1000);
gameStart = true;
}
break;
case "pause":
if (gameStart === true && timer !== null) {
clearInterval(timer);
gameStart = false;
}
break;
case "continue":
if (gameStart === false && timer !== undefined && timer !== null) {
timer = setInterval(callTimer, 1000);
gameStart = true;
}
break;
case "stop":
if (timer !== null) {
timer = null;
gameStart = false;
}
break;
}
$(".notes").text(status);
}
As u can see from the code u can use the method "clearInterval(nameOfTheTimer)" to pause the interval, if u want to reset it u have to reset the timer variable.
Hope it will help! :D

Use that:
Function.prototype.scope = function(context) {
var f = this;
return function() {
return f.apply(context, arguments);
};
};
Timer = function() {
this.tick = 0;
this.intervalId = null;
this.period = 1000; // in ms
this.isPaused = false;
};
jQuery.extend(Timer.prototype, {
onTick: function() {
if (!this.isPaused) {
this.tick++;
}
},
start: function() {
this.intervalId = setInterval(function() {this.onTick()}.scope(this), this.period);
},
pause: function() {
this.isPaused = !this.isPaused;
},
stop: function() {
clearInterval(this.intervalId);
var result = this.tick;
this.tick = 0;
this.isPaused = false;
return result;
}
});
t = new Timer();
t.start();
t.pause();
t.stop();

Stop the Timer the way you started it. What is the trigger? On what event the timer started?

Related

Debounce return timer

I don't understand the principle of operation. I have a code in which I have to create a delay of 2 seconds during the twist but during the delay script should not work using the debounce script but for some reason it always returns some timer and not an answer from function that the debounce script accepts
function debounce(f, ms) {
let timer = null;
return function(...args) {
const onComplete = () => {
f.apply(this, args);
timer = null;
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(onComplete, ms);
};
}
var delay = false;
$('.window').on('mousewheel', function(event) {
var pozition = $(document).scrollTop();
var block2 = $(".main_step").offset().top
var elemId = $(this).attr('id'),
scrollDir = event.deltaY;
var indicatorL = $(".indicator_main").data("counter");
if (elemId == 'steps' && scrollDir < 0 && delay === false) {
if (indicatorL != "4") {
$("#sli-" + indicatorL).css("display", "none");
indicatorL = indicatorL + 1;
$("#sli-" + indicatorL).css("display", "block");
$(".indicator_main").data("counter", indicatorL);
$(".indicator_main").animate({
"left": "+=25%"
}, "slow");
$(".indicator_num").text("0" + indicatorL);
$(".step_nr").text("0" + indicatorL);
}
}
delay = true;
var f = function() {
var delay = false;
return delay;
};
delay = debounce(f, 2000);
console.log(delay);
});

javascript function delay or set time out not working

i am trying to code the typed jquery functinality in javascript.I am almost there.HEre i need to add a delay after loading the word.like a few secons(lest say 4 sec) after each word loaded. How can i do it. In tried delay and set time out.It is not working for me or i am placing in wrong position. How can i set it.
var count = 0,
count2 = 0,
arr = ["SWOO", "EXCITE", "WOW", "AMAZE", "IMPRESS", "EDUICATE"],
dir = true;
setInterval(function() {
var interval = setInterval(function() {
document.getElementById('p1').innerHTML = arr[count].substring(0, count2);
if (dir) {
count2++;
if (count2 >= arr[count].length) {
dir = false;
}
} else {
count2--;
if (count2 < 0) {
dir = true;
clearInterval(interval);
}
}
}, 100);
count++;
if (count == 6) count = 0;
}, 2500);
<div style="width=100%">
<span id="p1" className="p2 hero-text-animate"></span> <span>them with video</span>
</div>
Your implementation will have problems if you add “A very long string” in to the array.
I’ve modified your code, hope it will help.
var count = 0,
count2 = 0,
arr = ["SWOO", "EXCITE", "WOW", "AMAZE", "IMPRESS", "EDUICATE"],
dir = true;
var p1 = document.getElementById("p1");
// Turning the intervals to on or off.
var onOff = function(bool, func, time) {
if (bool === true) {
interval = setInterval(func, time);
} else {
clearInterval(interval);
}
};
var eraseCharacters = function() {
// How long we want to wait before typing.
var wait = 1000;
// How fast we want to erase.
var erasingSpeed = 100;
var erase = function() {
p1.innerHTML = arr[count].substring(0, count2);
count2--;
if (count2 < 0) {
dir = true;
// Stop erasing.
onOff(false);
count++;
if (count === 6) {
count = 0;
}
// Start typing.
setTimeout(startTyping, wait);
}
};
// Start erasing.
onOff(true, erase, erasingSpeed);
};
var startTyping = function() {
// How long we want to wait before erasing.
var wait = 4000;
// How fast we want to type.
var typingSpeed = 100;
var type = function() {
p1.innerHTML = arr[count].substring(0, count2);
if (dir) {
count2++;
if (count2 > arr[count].length) {
dir = false;
// Stop typing.
onOff(false);
// Start erasing.
setTimeout(eraseCharacters, wait);
}
}
};
// Start typing.
onOff(true, type, typingSpeed);
};
// Start typing after 2 seconds.
setTimeout(startTyping, 2000);
<div style="width=100%">
<!-- Maybe it should be class. -->
<span id="p1" className="p2 hero-text-animate"></span> <span>them with video</span>
</div>

Break while loop with timer?

I was wondering is it possible to break a while loop with a timer?
looked on the internet but could not find a solution for it.
while (true) {
alert('hi');
} if (timer < 0) {
timer?
document.write('Time is up!');
break;
}
Thank you.
You should use setTimeout for this.
var timer = 3;
setTimeout(excuteMethod, 1000);
function excuteMethod() {
alert(timer + ' call');
timer--;
if (timer >= 0) setTimeout(excuteMethod, 1000);
}
Demo : http://jsfiddle.net/kishoresahas/9s9z7adt/
I'm not sure if this is the correct approach, but it works,
(function() {
var delay = 30;
var date = new Date();
var timer = date.setTime(date.getTime() + delay);
var count = 0;
function validate() {
var now = new Date();
if (+now > timer)
return false;
else
return true;
}
while (true) {
count++;
console.log(count);
if (!validate()) {
console.log("Time expired");
break;
}
// Fail safe.
if (count > 50000) {
console.log("Count breached")
break;
}
}
})()
You can change control value in timer function and break the loop.
var control = true;
while(control)
{
...
}
setTimeout(function(){
control = false;
}, delay); //delay is miliseconds
Or based on counter
var control = true,
counter = 10;
while(control){
...
}
// you can handle as count down
// count down counter every 1000 miliseconds
// after 10(counter start value) seconds
// change control value to false to break while loop
// and clear interval
var counterInterval = setInterval(function(){
counter--;
if(counter == 0)
{
control = false;
clearInterval(counterInterval);
}
},1000);

Return the value of a variable

Code:
var n = 360; // 6 min of waiting after blocked
function countDown() {
n--;
if (n > 0) {
setTimeout(countDown, 1000);
}
$("span#waitcount").html(document.createTextNode(n));
}
var count = 50; // Count of tokens when reached 0 block the page
var counter = document.getElementById('counter');
var clickDisabled = false;
$('.slotMachineButton').click(function() {
if (clickDisabled)
return;
setTimeout(function() {
count--;
counter.innerHTML = count;
if (count === 0) {
$.blockUI({message: '<h1>Thank you for Playing!!!<br>Please wait for 6 munites to be able to play again.</h1>'});
setTimeout(function() {
$.unblockUI({
onUnblock: function() {
alert('Game has been resumed!!!');
}
});
}, 10000);
setTimeout(countDown, 1000);
}
});
clickDisabled = true;
setTimeout(function() {
clickDisabled = false;
}, 3000);
}
Goal:
When the token count reaches 0 return it to original value to start again another count, because whenever the count reaches zero it goes -1 and keeps going.
When 6 min waiting is over start another waiting, I dont know if I got the code right for this part but please do check.
If you want to keep your code and you don't follow the suggestions in the the comments, then to this:
var n = 360, // 6 min of waiting after blocked
count = 50, // Count of tokens when reached 0 block the page
counter = document.getElementById('counter'),
clickDisabled = false;
function countDown(){
if(n > 0){
setTimeout(countDown, 1000);
} else {
n = 360;
clickDisabled = false
}
$("span#waitcount").html(document.createTextNode(n));
n--;
}
$('.slotMachineButton').click(function () {
if (clickDisabled) {
return;
}
setTimeout(function () {
counter.innerHTML = count;
if (count === 0) {
$.blockUI({ message: '<h1>Thank you for Playing!!!<br>Please wait or 6 munites to be able to play again.</h1>' });
setTimeout(function () {
$.unblockUI({
onUnblock: function () {
clickDisabled = true;
alert('Game has been resumed!!!');
setTimeout(countDown, 10);
}
});
}, 1000);
count = 50;
}
count--;
});
clickDisabled = true;
setTimeout(function () {
clickDisabled = false;
}, 100);
});
Bud you should realy look for a diffrent aproach. I changed the timer values for testing.

Infinite Loop in Page Redirection Function of JavaScript

I am now working on a piece of code of JavaScript which will be used to redirect a page with a shown counter. The problem is, when counter reaches 0, countDown() function gets in an infinite loop which causes the page to remain the same. And of course, I could not resolve the problem yet. Can anyone help?
You can see the problem here:
http://kibristaodtuvarmis.com/index.html
Code is shown below:
var time = 10;
var page = "http://blog.kibristaodtuvarmis.com";
function countDown()
{
if (time == 0)
{
window.location = page;
return(0);
}
else
{
time--;
gett("container").innerHTML = time;
}
}
function gett(id)
{
if(document.getElementById) return document.getElementById(id);
if(document.all) return document.all.id;
if(document.layers) return document.layers.id;
if(window.opera) return window.opera.id;
}
function init()
{
if(gett("container"))
{
setInterval(countDown, 1000);
gett("container").innerHTML = time;
}
else
{
setTimeout(init, 50);
}
}
document.onload = init();
EDIT:
I have done the below changes in countDown() function and problem is resolved:
var control = false;
function countDown()
{
if (time == 0 && control == false)
{
control = true;
window.location = page;
return(0);
}
else if (time > 0)
{
time--;
gett("container").innerHTML = time;
}
else
{
return(0);
}
}
I would do something like this:
var b = false;
if (time == 0 && b == false)
{
b = true;
window.location = page;
return(0);
}
Try this part of code for by replacing your complete javascript Code :
var time = 10;
var page = "http://blog.kibristaodtuvarmis.com";
function startCount() {
time = time - 1;
console.log(time);
document.getElementById("container").innerHTML = time;
startCounter();
}
function startCounter() {
if (time !== 0) {
setTimeout(function () {
startCount();
},1000);
} else {
location.href = page;
}
}
if (window.addEventListener) {
window.addEventListener("load", startCount, false);
} else if (el.attachEvent) {
window.attachEvent("load", startCount);
}
I tried it, It works.
Tell me your reply after testing.
Are you wanting it to stop at 0? Assign the setInterval to a var and then use clearInterval if 0
your setIinterval continues executing before change the window.location and then causes this loop because time is 0 and should launch window.location again
you should clear the interval
var IdInterval = setInterval(function () {
//.... code
}, 10000);
and after the first execution of countDown with time==0 then:
clearInterval(IdInterval);

Categories

Resources