How to do an animation in Javascript with pause and play options? - javascript

function animate(elem,style,from,to,time) {
if (!elem) return;
var start = new Date().getTime(),
timer = setInterval(function() {
var step = Math.min(1, (new Date().getTime() - start) / time);
elem.style[style] = (from + step * (to - from))+'px';
if (step == 1) clearInterval(timer);
}, 25);
elem.style[style] = from + 'px';
}
Here is my code. and i need to pause and play in it

Finally i found the answer
function animate(elem,style,to,time,callback)
{
if(!elem) return;
_animating = true;
curAnimElem = elem; /*stores the current Element*/
curStyle = style; /*stores the current style*/
curTo = to; /*stores the current to 'px'*/
curCallback = callback; /*stores the current callbak function*/
if(style === 'left'){ from = elem.offsetLeft; }
else if(style === 'top'){ from = elem.offsetTop; }
var start = new Date().getTime(),
animTimer = setInterval(function()
{
if(!pauseV)
{
pauseTime = Math.round(time - (new Date().getTime()-start));
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+'px';
if( step == 1 ){ _animating = false; clearInterval(animTimer); if(callback){callback(); callback = null;} }
}
else{clearInterval(animTimer);}
},25);
elem.style[style] = from + 'px';
}
the above code is to animate the elements(left or top only). to PAUSE and PLAY, include the below code in pause/play event function.
function pauseFun()
{
if(pauseV)
{
pauseV = false;
if(_animating){ animate(curAnimElem,curStyle,curTo,pauseTime,curCallback); }
}
else if(!pauseV)
{pauseV = true;}
}
Its works for me......
Thanks.

Use clearInterval(timer) to pause the animation and then timer = setInterval(...) again to resume it. You would need to break the setInterval callback out into its own named function (inside the body of the first function) to make resuming easier.

try this:
var doAnimation=true;
var timer=0;
var start=undefined;
function animate(elem,style,from,to,time)
{
if(!elem && doAnimation) return;
if(start==undefined)start = new Date().getTime();
timer = setInterval(function(){
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+'px';
if( step == 1){
doAnimation=false;
clearInterval(timer);
elem.style[style] = from+'px';
start=undefined;
}},25);
}
function fun(){
doAnimation=!doAnimation;
if(doAnimation){play();}
else{pause();}
}
function play(){
animate( document.getElementById('box'),'left',0 , 200, 7000);
}
function pause(){
clearInterval(timer);
}
$(document).ready(function(){
play();
});
Check out the fiddle here:
http://jsfiddle.net/sunnykumar08/V9MHN/1/

Related

requestFrameAnimation is choppy using duration

I'm writing a fadeIn function for an HTMLElement, the animation works but it's a bit choppy at the moment. what it does is animate a fadeIn from 0 opacity to 1, it also animates over a duration using requestFrameAnimation that's why it's probably so choppy, can someone help me make my animation run more smoothly. and example is on codepen.io look at the header fadeIn and see what I mean
fadeIn: function(duration) {
var el = this.$el,
duration,
end = 0;
el.style.opacity = 0;
el.style.display = "block";
var step = function() {
var current = +new Date(),
remaining = end - current;
if(remaining < 60) {
if(el) {
end = current + duration;
var val = parseFloat(el.style.opacity);
if (!((val += .1) > 1)) {
el.style.opacity = val;
}
} else {
return;
}
}
requestAnimationFrame(step);
};
step();
},
The smoothest one you can do is using CSS transition. But if you want to do with pure Javascript, you can do something like this
function fadeIn(dom, duration) {
let start = null;
const step = (end) => {
if (start === null) start = end;
let dt = end - start;
dom.style.opacity = Math.min(1, dt / duration);
if (dt < duration) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
function fadeOut(dom, duration) {
let start = null;
const step = (end) => {
if (start === null) start = end;
let dt = end - start;
dom.style.opacity = Math.max(0, 1 - dt / duration);
if (dt < duration) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
fadeIn(document.getElementById('your_dom'), 2000);

how to trigger the increment only once

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

Making a timer with code that can easily be reset

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>

Javascript - Check if key was pressed twice within 5 secs

I want to check if Enter key was pressed twice within 5 secs and perform some action.
How can I check if the key was pressed once or twice within a given time and perform different actions.
Here is my code:
<h1 id="log">0</h1>
<br/>
<span id="enteredTime">0</span>
<script>
$(document).keypress(function(e) {
if(e.which == 13){
var element = $("#log");
var timeDifference = 0;
//Log the timestamp after pressing Enter
$("#enteredTime").text(new Date().getTime());
//Check if enter was pressed earlier
if ($("#enteredTime").text() !== "0") {
var now = new Date().getTime();
var previous = $("#enteredTime").text();
difference = now - previous;
}
//Check if enter was pressed only once within 5 secs or more
if(){
$("#log").text("Once");
$("#enteredTime").text("0");
//Check if enter was pressed twice in 5 secs
}else{
$("#log").text("Twice in less than 5 secs");
$("#enteredTime").text("0");
}
}
});
</script>
http://jsfiddle.net/Rjr4g/
Thanks!
something like
var start=0;
$(document).keyup(function(e) {
if(e.keyCode == 13) {
elapsed = new Date().getTime();
if(elapsed-start<=5000){
//do something;
}
else{
//do something else;
}
start=elapsed;
}
});
Try a timer based solution like
var flag = false,
timer;
$(document).keypress(function (e) {
var element = $("#log");
var timeDifference = 0;
if (e.which == 13) {
if (flag) {
console.log('second');
clearTimeout(timer);
flag = false;
} else {
console.log('first');
flag = true;
timer = setTimeout(function () {
flag = false;
console.log('timeout')
}, 5000);
}
//Log the timestamp after pressing Enter
$("#enteredTime").text(new Date().getTime());
if ($("#enteredTime").text() !== "0") {
var now = new Date().getTime();
var previous = $("#enteredTime").text();
difference = now - previous;
}
}
});
Demo: Fiddle
Bacon.js seems like a good tool to express this.
$(document).asEventStream('keypress')
.filter(function (x) {
return x.keyCode == 13;
})
.map(function () {
return new Date().getTime();
})
.slidingWindow(2, 1)
.map(function (x) {
return (x.length == 1 || x[1] - x[0] > 5000) ? 1 : 2;
})
.onValue(function (x) {
$("#log").text(x == 1 ? "Once" : "Twice in less than 5 secs");
});
(fiddle)
here is my solutions, please check it if match your idea :)
(function($){
var element = $("#log");
var timeDifference = 0;
var count = 0;
$(document).keypress(function(e) {
if(e.which === 13){
//do what you want when enterpress 1st time
/*blah blah */
//after done 1st click
count++;
if(count === 2) {
//do what you want when enterpress 2nd time in 5 seconds
/* blah blah */
//after done
clearTimeout(watcher);
count = 0;
return;
}
//setTimeout to reset count if more than 5 seconds.
var watcher = setTimeout( function() {
count = 0;
},5000);
}
});
}(jQuery)
Check your Updated Fiddle
var count = 0;
$(document).keypress(function(e) {
var element = $("#log");
var timeDifference = 0;
if(e.which == 13){
count++;
console.log('enter pressed'+count);
if(count == 1){
startTimer();
}
else{
checkCount();
}
//Log the timestamp after pressing Enter
$("#enteredTime").text(new Date().getTime());
if ($("#enteredTime").text() !== "0") {
var now = new Date().getTime();
var previous = $("#enteredTime").text();
difference = now - previous;
}
}
});
function startTimer(){
setTimeout(checkCount,5000);
}
function checkCount(){
if(count == 1){
$("#log").text("Once");
$("#enteredTime").text("0");
//Check if enter was pressed twice in 5 secs
}else{
$("#log").text("Twice in less than 5 secs");
$("#enteredTime").text("0");
}
}
startTimer() starts counting on first enter press. And checkCount() contains your condition after 5secs.
setTimeout() lets you attach an event which occurs after a specific timespan.

setInterval animation

http://jsfiddle.net/vzBZB/5/
(function(){
var i = 1;
var start = true;
setInterval(function(){
if (i>0&&start){
var o = $("#box").css("opacity");
var s = parseFloat(o) - 0.1;
$("#box").css("opacity", s.toString());
i = s;
}
else {
start = false;
var o = $("#box").css("opacity");
var s = parseFloat(o) + 0.1;
$("#box").css("opacity", s.toString());
i = s;
if (i==1) start = true;
}
}, 100);
})();
This code does simple animation - it goes from opacity 1 to 0 and back to 1. But i would like to perform this cycle infinitely. i used if (i==1) start = true; but it doesnt help. how do i fix? Second question: when it stops opacity is 1.1. Why? How do i fix?
How about just set "start" back to true when you're done fading back in. Such as:
start = false;
var o = $("#box").css("opacity");
var s = parseFloat(o) + 0.1;
$("#box").css("opacity", s.toString());
i = s;
if(s >= 1) start = true; //Reset for next loop
Here's my working example: http://jsfiddle.net/vzBZB/8/
You may find it easier to simply use the callback parameter of .fadeToggle recursively. See my update to your jsfiddle: http://jsfiddle.net/vzBZB/6/.
You arent setting start back to true when it gets back to full opacity...
add this
if (o >= 1){
start=true;
}
full code:
(function(){
var i = 1;
var start = true;
setInterval(function(){
if (i>0&&start){
var o = $("#box").css("opacity");
var s = parseFloat(o) - 0.1;
$("#box").css("opacity", s.toString());
i = s;
}
else {
start = false;
var o = $("#box").css("opacity");
var s = parseFloat(o) + 0.1;
$("#box").css("opacity", s.toString());
i = s;
if (o >= 1){
start=true;
}
}
}, 100);
})();

Categories