To create a ticking movement and not a sliding one of a number on a canvas i want to move the number up in 0,2 secondes and wait 0,8 seconds. The codes works good for a sliding movement but to implement the ticking i get lost.
jsfiddle
var ittt = 0;
var add = null;
function MinuteTimer() {
add = setInterval(function () {
totime();
if (ittt % (40 * 60) == 0) {
ittt = 0;
}
}, 5);
};
function stoptimer() {
clearInterval(add);
};
function totime() {
drawcanvasbackground();
drawnumberscanvas(ittt);
ittt += 1;
if (ittt % 40 == 0 && ittt > 0) {
clearInterval(add);
setTimeout(MinuteTimer(), 800);
};
};
Related
I have a function that will perform an action when the timer reaches 5000ms:
var timer = new Timer(function () {
console.log("refreshingBid");
refreshBid();
}, 5000);
timer.pause();
if (isElementInViewport() === true) {
console.log("element in view");
timer.resume();
} else {
timer.pause();
console.log("element is out of view")
}
//I am trying to loop this 5 times with the 5000ms delay - the code I am using for this is:
for (i=0;i<=5;i++)
{
MyFunc();
}
It seems regardless of whether I put the for loop in the timer or whether I put the timer inside the for loop the result is the same where all 5 loops happen instantaneously instead of with a delay of the timer being applied? I'm not sure what i'm doing wrong here... Any help would be appreciated!
Sorry, edit to include the complete code below:
<script>
var iframe2 = document.getElementById('postbid_if');
function isElementInViewport() {
var el = document.getElementById('postbid_if')
console.log(el)
var rect = el.getBoundingClientRect();
console.log(rect)
return rect.bottom >= 0 &&
rect.right >= 0 &&
rect.left < (window.innerWidth || document.documentElement.clientWidth) &&
rect.top < (window.innerHeight || document.documentElement.clientHeight);
}
function Timer(callback, delay) {
var timerId, start, remaining = delay;
this.pause = function () {
window.clearTimeout(timerId);
remaining -= new Date() - start;
};
this.resume = function () {
start = new Date();
window.clearTimeout(timerId);
timerId = window.setTimeout(callback, remaining);
};
this.resume();
}
for (i = 0; i <= 5; i++) {
MyFunc();
}
var timer = new Timer(function () {
console.log("refreshingBid");
refreshBid();
}, 5000);
timer.pause();
if (isElementInViewport() === true) {
console.log("element in view");
timer.resume();
} else {
timer.pause();
console.log("element is out of view")
}
</script>
It's because it's looping through quickly 5 times then all 5 loops are delaying after the 5 seconds. The timeout pauses it after 5 seconds, not for 5 seconds up front.
Perhaps you could revise your code in this way to achieve the timer based iterations as required:
//Track the current iteration
var i = 0;
function MyFunc() {
var timer = new Timer(function () {
console.log("refreshingBid");
refreshBid();
// The current timer has completed. If the current
// iteration is less than 5...
if(i < 5) {
i++;
// .. then start another timer for the next iteration
MyFunc();
}
}, 5000);
timer.pause();
if (isElementInViewport() === true) {
console.log("element in view");
timer.resume();
} else {
timer.pause();
console.log("element is out of view")
}
}
// Start the first iteration
MyFunc();
I have used the setTimeout function so my object stays on y<0 for a while and at that time i want to my increment to trigger only once but it keeps on triggering ...more i delay my function using the setTimeout function higher times the increment operation gets trigger......so what is the solution through which my increment triggers only once no matter how long my object stays in y<0
Player.prototype.checkInWater = function () {
if (this.y < 0) {
++scoreGot
setTimeout(function(){
player.x = 202;
nplayer.y = 405;
}, 300);
}
};
Player = function(){
....
this.checkedInWater = false;
}
Player.prototype.checkInWater = function () {
if (this.y < 0 && !this.checkedInWater) {
++scoreGot;
t = this;
t.checkedInWater = true;
setTimeout(function(){
player.x = 202;
nplayer.y = 405;
t.checkedInWater = false;
}, 300);
}
};
I am making a simple podomoro clock, and everything seems to work fine except when timer reaches 0 its doesn't entirely stop. Minutes seem to stop but seconds keep decrementing. I think there might be something wrong with my startTimer function but I've tried tinkering with it for hours to no result.
JS:
$(document).ready(function() {
var pomoTime = $('#pomodoroNum');
var breakTime = $('#breakNum');
var status = $('#timerStatus');
var timerDisplay = $('#timer');
var startButton = $('#startBtn');
var stopButton = $('#stopBtn');
var state = 1; // 1=stopped 2=running
var countDown; // intervalID;
var minutes = 0;
var seconds = 60;
startButton.click(function() {
if (state == 1) { // if timer is not running then start timer
startTimer(minutes, seconds);
$('#breakMinus').off("click");
$('#breakPlus').off("click");
$('#workMinus').off("click");
$('#workPlus').off("click"); // disable +- controls when timer starts
};
});
updateDisplay(); // initially controls are enabled at the start
stopButton.on("click", function() {
if (state == 2) {
pauseTimer();
state = 1;
updateDisplay(); // renable +- controls when timer stops
}
});
function startTimer(m, s) {
state = 2;
var startMinutes = m;
var startSeconds = s;
countDown = setInterval(function() {
startSeconds--;
startMinutes = ("0" + startMinutes).slice(-2); // double digits conversion if <10
startSeconds = ("0" + startSeconds).slice(-2);
minutes = ("0" + startMinutes).slice(-2); // update minutes and seconds so when timer is stopped, it can resume from where it left off when startButton is pressed.
seconds = ("0" + startSeconds).slice(-2);
timerDisplay.html(startMinutes + ":" + startSeconds);
if (startSeconds == 0 && startMinutes > 0) {
startMinutes-- // decerement minutes when seconds 0...
startSeconds = 60; // ..and reset seconds to 60
}
}, 1000);
if (startMinutes == 0 && startSeconds == 0) {
clearInterval(countDown);// <-- not clearing here
}
};
function pauseTimer() {
clearInterval(countDown);
};
function updateDisplay() {
// break +-
$('#breakMinus').on("click", function() {
status.html("Break");
if (breakTime.text() > 1) {
breakTime.text(+breakTime.text() - 1);
};
timerDisplay.text(breakTime.text());
});
$('#breakPlus').on("click", function() {
status.html("Break");
breakTime.text(+breakTime.text() + 1); // parseInt to covert string into number so it doesn't concatanate.
timerDisplay.text(breakTime.text());
});
// work +-
$('#workMinus').on("click", function() {
status.html("Work");
if (pomoTime.text() > 1) {
minutes = pomoTime.text() - 2;
}
seconds = 60;
if (pomoTime.text() > 1) {
pomoTime.text(+pomoTime.text() - 1);
};
timerDisplay.text(pomoTime.text());
});
$('#workPlus').on("click", function() {
minutes = pomoTime.text();
seconds = 60;
status.html("Work");
pomoTime.text(+pomoTime.text() + 1); // parseInt to covert string into number to prevent concatanation.
timerDisplay.html(pomoTime.html());
});
};
});
example: http://codepen.io/aliz16/pen/OXMwRJ
Your check for the stop condition is outside of your interval function. That's why it's never stopping. Move the condition inside the function and use <= to be extra safe:
if (startSeconds <= 0 && startMinutes > 0) {
startMinutes -= 1; // decerement minutes when seconds 0...
startSeconds += 60; // ..and reset seconds to 60
}
if (startMinutes <= 0 && startSeconds <= 0) {
clearInterval(countDown);
}
}, 1000);
I'm making a shot clock for my school's basketball team. A shot clock is a timer that counts down from 24 seconds. I have the skeleton for the timer right now, but I need to have particular key bindings. The key bindings should allow me to rest, pause, and play the timer.
var count=24;
var counter=setInterval(timer, 1000);
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count + " secs";
}
I'm not sure what you meant by "rest" the timer, I interpret this as "pause", so:
Space = Pause / Play.
R = Reset.
var
count=24,
counter = setInterval(timer, 1000),
running = true;
function timer() {
count -= 1;
if (count <= 0) {
clearInterval(counter);
}
document.getElementById("timer").innerHTML = count + " secs";
}
window.addEventListener("keydown", function(e) {
switch(e.keyCode) {
case 32: // PLAY
running ? clearInterval(counter) : counter = setInterval(timer, 1000);
running = !running;
break;
case 82: // RESET
clearInterval(counter);
document.getElementById("timer").innerHTML = 24 + " secs";
count = 24;
running = false;
}
});
<div id="timer">24 secs</div>
I am not able to comment yet, but I recommend checking out this post Binding arrow keys in JS/jQuery
The linked post explains how to bind arrow keys using js/jquery. Using http://keycode.info/ you can find out the keycodes of your desired keys and replace the current values then continue to build your code from there.
Here is my code sample: http://codepen.io/anon/pen/vLvWJM
$(document).ready(function() {
var $timer = $('#timer');
var $timerStatus = $('#timerStatus');
var timerValue = 24;
var intervalId = null;
var timerStatus = 'stopped';
if(!$timer.length) {
throw 'This timer is missing a <div> element.';
}
$(document).keydown(function(k) {
if(k.which == 80) {
if(timerStatus === 'playing') {
clearInterval(intervalId);
timerStatus = 'stopped';
updateTimerStatus();
return;
}
intervalId = setInterval(function() {
playTimer();
timerStatus = 'playing';
updateTimerStatus();
}, 1000);
} else if(k.which == 82) {
clearInterval(intervalId);
resetTimer();
updateText();
timerStatus = 'stopped';
updateTimerStatus();
}
});
function playTimer() {
if(timerValue > 0) {
timerValue--;
updateText();
}
}
function resetTimer() {
timerValue = 24;
}
function updateText() {
$timer.html(timerValue);
}
function updateTimerStatus() {
$timerStatus.html(timerStatus);
}
});
<div id="timerStatus">stopped</div>
<div id="timer">24</div>
I am trying to get this script to count up to a specified number and back down to a specified number as follows: 19200, 38400, 57600, 76800, 96000, 76800, 57600, 38400, 19200 — repeatedly. So far this is what I have but I cannot seem to make it count down in the order above, it restarts from 19200 again.
$(function() {
var seconds = 19200;
var timerId = setInterval(function() {
seconds = seconds + 19200;
$("#counter").text(seconds);
if (seconds > "76800") {
clearInterval(seconds);
seconds = seconds - "19200";
}
}, 500);
});
A little issue with the logic, the condition
if (seconds > "76800") {
would always try to keep the seconds above 76800.
Rather you would want a flag to track the direction of the count. Check out below:
UPDATED:
Working demo at
JSFiddle
$(function () {
var increment = 19200;
var seconds = increment;
var countUp = true;
var timerId = setInterval(function () {
$("#counter").text(seconds);
if (countUp) {
seconds += increment;
} else {
seconds -= increment;
}
if (countUp && seconds > increment*4) {
countUp = false;
} else if (!countUp && seconds <= increment) {
countUp = true;
}
}, 500);
});
Check the below function
$(function() {
var seconds = 19200;
action = 'add';
var timerId = setInterval(function() {
$("#counter").text(seconds);
if (seconds == 96000) {
action = 'remove';
} else if (seconds == 19200) {
action = 'add'
}
if (action == 'add')
seconds += 19200;
else if (action == 'remove')
seconds -= 19200;
}, 500);
});
I think this is a little more elegant
var increment = 19200,
seconds = increment;
var timer = setInterval(function() {
console.log(seconds);
seconds += increment;
if (seconds > 76800 || seconds < 19200) {
increment *= -1;
}
}, 500);
jsfiddle