Reset animation to original position using javascript - javascript

using the following script i was able to move my picture right when clicked:
<script>
var myTimer = null;
function move(){
document.getElementById("fish").style.left =
parseInt(document.getElementById("fish").style.left)+1+'px';
}
window.onload=function(){
document.getElementById("fish").onclick=function(){
if(myTimer == null){
myTimer = setInterval("move();", 10);
}else{
clearInterval(myTimer);
myTimer = null;
}
}
}
</script>
I am having some trouble reseting the picture to original location without using jQuery.
If anyone can help that would be much appreciated.

If you capture the original position ahead of time you can reset later to the captured value:
var originalPosition = document.getElementById("fish").style.left;
function resetPosition() {
document.getElementById("fish").style.left = originalPosition;
}

Use external JavaScript. Some code to look at:
var pre = onload, E, doc, bod;// previous onload
onload = function(){
if(pre)pre();
doc = document; bod = doc.body;
E = function(id){
return doc.getElementById(id);
}
var fish = E('fish'), timer;
fish.onclick = function(){
if(!timer){
timer = setInterval(function(){
fish.style.left = parseInt(fish.style.left)+1+'px';
}, 10);
}
else{
clearInterval(timer); timer = false;
fish.style.left = '0'; // change '0' to what your CSS `left:`value is
}
}// end load

This should work fine,
var myTimer = null;
var startX = 0;
function move(){
document.getElementById("fish").style.left =
parseInt(document.getElementById("fish").style.left)+1+'px';
}
window.onload=function(){
document.getElementById("fish").onclick=function(){
if(myTimer == null){
startX = document.getElementById("fish").style.left;
myTimer = setInterval("move();", 10);
}else{
clearInterval(myTimer);
myTimer = null;
document.getElementById("fish").style.left = startX + "px";
}
}
}

Related

How to decrement given time

I am getting an output of 00:20:00 which is correct but my problem now is its not decrementing even when I have subtracted it am i missing something?
$duration=0;
$startime=date('Y-m-d H:i:s');
$end_time=$end_time=date('Y-m-d H:i:s',
strtotime('+'.$duration.'minutes',strtotime($startime)));
$timefirst=strtotime($startime);
$timesecond=strtotime($end_time);
$differenceinseconds=$timesecond-$timefirst;
echo gmdate("H:i:s", $differenceinseconds);
my script
<div id='response'></div>
<script type="text/javascript">
setInterval(function(){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",'responseTime.php',false);
xmlhttp.send(null);
document.getElementById('response').innerHTML=xmlhttp.responseText;
},1000);
</script>
As RiggsFolly mentioned why waste servers time running a timer.
Here is what you can do in javascript,
<div id="stopwatch"></div>
<script>
var Stopwatch = function (elem, target, options) {
var timer = createTimer(),
offset,
clock,
interval;
// default options
options = options || {};
options.delay = options.delay || 1;
// append elements
elem.appendChild(timer);
// initialize
reset();
// private functions
function createTimer() {
var interval = 20 ; // 20 seconds
var element = document.createElement("progress");
element.setAttribute("max",interval);
return element;
}
function start() {
if (!interval) {
offset = Date.now();
interval = setInterval(update, options.delay);
}
}
function stop() {
if (interval) {
clearInterval(interval);
interval = null;
}
}
function reset() {
clock = 0;
render();
}
function update() {
clock += delta();
render();
}
function render() {
timer.value = parseInt(clock / 1000);
if(timer.value==interval){
// This is the point where timer ends, put your further code in here.
}
}
function delta() {
var now = Date.now(),
d = now - offset;
offset = now;
return d;
}
// public API
this.start = start;
this.stop = stop;
this.reset = reset;
};
var elem = document.getElementById("stopwatch");
var timer = new Stopwatch(elem, {delay: 10});
timer.start();
</script>

How can I do this dynamically?

I am working on writing my code this way, but I want to do it in a loop. I want to be dynamic. How can I do it?
$("#sound-player").attr("src",secilen[0]);
var x = document.getElementById("sound-player");
x.play();
x.onended = function() {
$("#sound-player").attr("src",secilen[1]);
var x = document.getElementById("sound-player");
x.play();
x.onended = function() {
$("#sound-player").attr("src",secilen[2]);
var x = document.getElementById("sound-player");
x.play();
x.onended = function() {
$("#sound-player").attr("src",secilen[3]);
var x = document.getElementById("sound-player");
x.play();
x.onended = function() {
alert("bitti");
}
}
}
}
You can use recursion:
/* Cache the player. */
var x = document.getElementById("sound-player");
/* Create an IIFE and execute it recursively. */
(function playRecursively (current, last) {
x.src = secilen[current];
x.play();
x.onended = function() {
/* Play the next, if the current is not the last. */
if (current < last) playRecursively(++current, last);
else alert("bitti");
};
})(0, secilen.length - 1);
Reuse your variable x, instead o redefining it.
var player = document.getElementById('sound-player');
var i = 0;
function playSource(src){
// change the src attribute and play.
if (secilen[scr] !== undefined) {
player.setAttribute('src', secilen[src]);
player.play();
}
else {
alert('bitti')
}
}
player.onended = function(){
i++;
playSource(i);
}
playSource(i); //start playing the first sound

Start/stop setTimeout with a button & prevent counting faster with more clicks

I am working with JavaScript and I use a setTimeout function in order to count up. Here is my code...
<button id="star">Start</button>
<p id="time">0</p>
var timeEl = 0;
function start() {
time();
}
function time() {
setTimeout(function() {
timeEl = timeEl + .1;
timeEnd = timeEl.toFixed(1);
document.getElementById("time").innerHTML = timeEnd;
time();
}, 100);
}
var el = document.getElementById("star");
el.addEventListener("click", star, false);
How do I get my setTimeout function to start on stop when I click on the button
How to prevent my counting from going faster the more times I click on the button.
I have included my JSFiddle below!
https://jsfiddle.net/pb4759jh68/0618eLoe/
To stop a timer you can use clearTimeout(), but it does require the id of the timer created with setTimeout(). The call to setTimeout() now saves the timer id in timeOut and then checks the contents of timeOut in start() to see whether a timer is currently running. If a timer is running then timeOut is used in clearTimeout(timeOut);.
var timeEl = 0;
var timeOut = null;
function start()
{
if(timeOut !== null){
clearTimeout(timeOut);
timeOut = null;
}else{
time();
}
}
function time()
{
timeOut = setTimeout(function()
{
timeEl = timeEl + .1;
timeEnd = timeEl.toFixed(1);
document.getElementById("time").innerHTML = timeEnd;
time();
}, 100);
}
var el = document.getElementById("star");
el.addEventListener("click", start, false);
I hope this code clears the issue
JSFiddle
The same can be achieved using setInterval and clearInterval. Try this JSFiddle
Every time the button is pressed, you get a second copy of your timer running, which is advancing your time faster.
var el = document.getElementById("star");
el.addEventListener("click", start, false);
I would recommend something like this:
var timerId = 0;
var timeEl = 0;
function start()
{
time();
}
function time()
{
timerId = setTimeout(function()
{
timeEl = timeEl + .1;
timeEnd = timeEl.toFixed(1);
document.getElementById("time").innerHTML = timeEnd;
time();
}, 100);
}
var el = document.getElementById("star");
el.addEventListener("click", function() {
if (timerId !== 0) {
clearTimeout(timerID);
timerId = 0;
} else {
start();
}
}, false);
You can cancel a previously set timeout with clearTimeout - see https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout.
try this
JsFiddle
var timeEl = 0,timer;
function start()
{
time();
}
function time()
{
document.getElementById("star").disabled=true;
timer=setTimeout(function()
{
timeEl = timeEl + .1;
timeEnd = timeEl.toFixed(1);
document.getElementById("time").innerHTML = timeEnd;
time();
}, 100);
}
function stop(){
document.getElementById("star").disabled=false;
clearTimeout(timer);
}
var el = document.getElementById("star");
el.addEventListener("click", start, false);
var elstop = document.getElementById("stop");
elstop.addEventListener("click", stop, false);
I simply added a boolean that states if the counting is already running :
https://jsfiddle.net/0618eLoe/3/
var timeEl = 0;
var isStarted = false;
function startStop()
{
if (!isStarted) {
isStarted = true;
time();
} else {
isStarted = false;
}
}
function time()
{
if (!isStarted) return;
setTimeout(function()
{
timeEl = timeEl + .1;
timeEnd = timeEl.toFixed(1);
document.getElementById("time").innerHTML = timeEnd;
time();
}, 100);
}
var el = document.getElementById("star");
el.addEventListener("click", startStop, false);
The following is a simple solution using setInterval and clearInterval
var time = 0.0;
var view = document.getElementById('time');
var running = false;
var repeat;
function start(){
if(running){
return;
}
running = true;
repeat = setInterval(increment, 100);
}
function stop(){
clearInterval(repeat);
running = false;
}
function increment(){
time += 0.1;
view.innerText = time.toFixed(1);
}
Demo:
https://jsfiddle.net/m7bmc2uj/
var timeEl = 0,g;
function start()
{
if(g){
clearTimeout(g);
timeEl = 0;
}
time();
}
function time()
{
g=setTimeout(function()
{
timeEl = timeEl + .1;
timeEnd = timeEl.toFixed(1);
document.getElementById("time").innerHTML = timeEnd;
time();
}, 100);
}
var el = document.getElementById("star");
el.addEventListener("click", start, false);
tell me what else would you need. or it implements your specification. here button click will start the timer from 0 again.
jsfiddle

Jquery Mobile stopwatch

Im trying to make a stopwatch in a JqueryMobile app. I've been following the guide from a previous post How to create a stopwatch using JavaScript?
This works but the function to create the button, essential just makes 3 links, where as I want them as buttons. So at present it will generate the html of:
start
where as I need it to be
start
I've played around with the function to try to get it to work, and even just added my own buttons into the HTML with hrefs of #start, #stop, #reset but cant get them to work
The function is:
function createButton(action, handler) {
var a = document.createElement("a");
a.href = "#" + action;
a.innerHTML = action;
a.addEventListener("click", function(event) {
handler();
event.preventDefault();
});
return a;
}
Add the classes ui-btn ui-btn-inline to the links in createButton. As you are using jQuery anyway, I hvae also updated the stopwatch to use jQuery for DOM manipulation:
(function($) {
var Stopwatch = function (elem, options) {
var timer = createTimer(),
startButton = createButton("start", start),
stopButton = createButton("stop", stop),
resetButton = createButton("reset", reset),
offset,
clock,
interval;
// default options
options = options || {};
options.delay = options.delay || 1;
var $elem = $(elem);
// append elements
$elem.empty()
.append(timer)
.append(startButton)
.append(stopButton)
.append(resetButton);
// initialize
reset();
// private functions
function createTimer() {
return $('<span class="swTime"></span>');
}
function createButton(action, handler) {
var a = $('<a class="' + action + ' ui-btn ui-btn-inline">' + action + '</a>');
a.on("click",function (event) {
handler();
event.preventDefault();
});
return a;
}
function start() {
if (!interval) {
offset = Date.now();
interval = setInterval(update, options.delay);
}
}
function stop() {
if (interval) {
clearInterval(interval);
interval = null;
}
}
function reset() {
clock = 0;
render();
}
function update() {
clock += delta();
render();
}
function render() {
timer.text(clock / 1000);
}
function delta() {
var now = Date.now(),
d = now - offset;
offset = now;
return d;
}
// public API
this.start = start;
this.stop = stop;
this.reset = reset;
};
$.fn.stopwatch = function(options) {
return this.each(function(idx, elem) {
new Stopwatch(elem, options);
});
};
})(jQuery);
$(document).on("pagecreate","#page1", function(){
$(".stopwatch").stopwatch();
});
DEMO

Namespacing in Javascript Classes

I'm trying to create a timer in Javascript and I have a specific issue with how I'm implementing it.
Right now it's like this
function CountUpTimer(seconds,name,targetId,submitButtonId){
this.time = seconds;
this.currentTime = 0;
this.minutes = Math.floor(seconds/60);
this.submitButtonId = submitButtonId;
this.seconds = seconds - this.minutes*60;
this.currentSeconds = 0;
this.currentMinutes = 0;
this.targetId = targetId;
this.name = name;
this.isPaused = false;
this.init = function(){
setInterval(this.name + ".tick()",1000);
}
this.pause = function(){
this.isPaused = true;
}
this.unpause = function(){
this.isPaused = false;
}
this.tick = function(){
if(this.isPaused == false){
if(this.currentTime <= this.time){
if(this.currentSeconds == 59){
this.currentSeconds = 0;
this.currentMinutes++;
}
this.updateTimer();
this.currentTime++;
this.currentSeconds++;
} else{
this.endTiming();
}
}
}
Now, the problem with this is that I can't dynamically create CountUpTimer objects, because I need to know the name of the variable that I am assigning to that object. Is there some way I can work around this - so let's say something like
setInterval(this.tick(),1000);
?
When using callback, you lose the context at execution.
You should use bind to keep the context.
setInterval(this.tick.bind(this),1000);
More details here
this.init = function(){
var self = this;
setInterval(self.tick(),1000);
}
Keep the reference to original object, because using this in setInterval will be in the wrong object context (document).
You can do:
var self = this;
setInterval(function() {
self.tick()
}, 1000);
Or use Function.bind if you are fine with non-legacy support.

Categories

Resources