How to decrement given time - javascript

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>

Related

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

How to Pause the timer on window blur and resume the timer on window focus event?

Thanks for seeing my question.
I am using wp-pro-quiz plugin for quiz. I want to know that how can I pause the timer if the window is not in focus or is blur and resume it when it is back to focus.?
My code:
I get reset when it get focused
var timelimit = (function () {
var _counter = config.timelimit;
var _intervalId = 0;
var instance = {};
instance.stop = function () {
if (_counter) {
window.clearInterval(_intervalId);
globalElements.timelimit.hide();
}
};
instance.start = function () {
var x;
var beforeTime;
if (!_counter)
return;
var $timeText = globalElements.timelimit.find('span').text(plugin.methode.parseTime(_counter));
var $timeDiv = globalElements.timelimit.find('.wpProQuiz_progress');
globalElements.timelimit.show();
$.winFocus(function (event) {
console.log("Blur\t\t", event);
},
function (event) {
console.log("Focus\t\t", event);
x = _counter * 1000;
beforeTime = +new Date();
});
_intervalId = window.setInterval(function () {
var diff = (+new Date() - beforeTime);
var elapsedTime = x - diff;
if (diff >= 500) {
$timeText.text(plugin.methode.parseTime(Math.ceil(elapsedTime / 1000)));
}
$timeDiv.css('width', (elapsedTime / x * 100) + '%');
if (elapsedTime <= 0) {
instance.stop();
plugin.methode.finishQuiz(true);
}
}, 16);
};
return instance;
})();
Use this wrapper function to pause, resume your timeout.
var Timer;
Timer = function(callback, delay) {
var remaining, start, timerId;
timerId = void 0;
start = void 0;
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();
};
Intialize it like this, timer = new Timer("callback_function_here", 45000)
In this case total time is 45 seconds for the callback and upon event triggers(blur or focus in your case) it will pause or resume the timer accordingly.
timer.pause() //pause the timer
timer.resume() //resume the timer
P.S - Use this function as per the logic of your code. You will have to make the timer calls accordingly in your code
I did it this way:
var time0 ; var setTimeout_Int; var focused = true; var resume_Fun ;
var addTime =0; var addTimeDiff =0;
window.onfocus = function() {
focused = true;
var d = new Date();
addTimeDiff = addTimeDiff +( d.getTime() - addTime );
resume_Fun();
};
window.onblur = function()
{
focused = false;
};
function init()
{
var d = new Date();
time0 = d.getTime();
setTimeout_Int = setTimeout(update, 1000 )
}
function update()
{
clearTimeout(setTimeout_Int);
var d = new Date();
if(focused)
{
if(d.getTime() -(time0+addTimeDiff) < 20000)
{
setTimeout_Int= setTimeout(update, 1000 )
}
}
else
{
addTime = d.getTime();
resume_Fun = update;
}
}
init();

Changer SetInterval Values After Interval

If I can try to make everyone understand what I am looking for, I am looking for the value of the interval to change to lets say "5000ms" after "1000ms" and then it would go on to the next value such as "2000ms" and repeat all over again! The current code I have is pretty much a stopwatch, It adds the number 1 to a paragraph every 1000ms. Any help is extremely appreciated!
<script>
function myFunction() {
clicks += 1;
}
setInterval(myFunction, 1000);
var clicks = 0;
function myFunction() {
clicks += 1;
document.getElementById("demo").innerHTML = clicks;
// connects to paragraph id
}
</script>
<p id="demo"></p>
<!--connects to getElementById-->
Don't use setInterval - this functions will perform the action in any given interval, which you set once.
Use setTimeout instead. Which performs the action only once after given interval, and then call it again and again with different interval values.
what about this
<script>
var clicks = 0;
myFunction(1000);
function myFunction( currentInterval ) {
clicks ++;
document.getElementById("demo").innerHTML = clicks;
if ( currentInterval == 1000 )
{
currentInterval = 5000;
}
else if ( currentInterval == 5000 )
{
currentInterval = 2000;
}
else
{
currentInterval = 1000;
}
setTimeout( function(){ myFunction( currentInterval ) }, currentInterval );
}
</script>
<p id="demo"></p>
you should try using recursive timeout instead of interval
var timeout = 1000;
var timer;
function startTimer() {
clearTimeout(timer);
timer = setTimeout(function() {
console.log('tick');
startTimer();
}, timeout);
}
startTimer();
// timeout = 2000
// timeout = 500
// clearTimeout(timer); to cancel
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
This might look a little complicated but you can try something like this:
JSFiddle.
(function() {
var interval = null;
var limit = 5;
function initInterval(callback, index) {
var msToSec = 1000;
if (interval) {
clearInterval();
}
console.log("Delay: ", index)
interval = setInterval(callback, index * msToSec);
}
function clearInterval() {
window.clearInterval(interval);
interval = null;
}
function resetInterval(callback, count) {
clearInterval();
initInterval(callback, count);
}
function main() {
var count = 1;
var notify = function() {
console.log("Hello World: ", count);
var _nextCount = ((count++) % limit) + 1;
if (count < 10) {
resetInterval(notify, _nextCount);
} else {
console.log("Stoping loop...");
clearInterval();
}
}
initInterval(notify, count);
}
main()
})()

Stopping a Javascript setInterval that is delayed by a setTimeout

I'm having issue with this jsfiddle snippet:
http://jsfiddle.net/y45jN/7/
var mainFunction = function() {
this.text;
this.repeater;
}
var repeatEvery = function(func, interval) {
var now = new Date();
var delay = interval - now % interval;
function start() {
var intervalID = setInterval(func, interval);
func(intervalID);
}
setTimeout(start, delay);
};
mainFunction.prototype.start = function(printText) {
this.text = printText;
var self = this;
var func = function(intervalID) {
if(intervalID){
this.repeater = intervalID;
}
document.getElementById('test').innerHTML += this.text + '<br/>';
};
repeatEvery(_.bind(func, this),1000);
}
mainFunction.prototype.stop = function() {
clearInterval(this.repeater);
}
var test = new mainFunction();
test.start('hello');
setTimeout(test.stop,10000);
My goal is to call the stop function and stop the Interval that has been set by the start function.
You need to do
setTimeout(function(){ test.stop()}, 10000)
or
setTimeout(test.stop.bind(test), 10000); //Bind method is not available in IE8 though
instead of
setTimeout(test.stop, 10000);
The reason for this is that Javascript loses track of the "this" when you pass a callback to a function.

Add duration to JS setTimeout after the timer is running

I'm trying to figure out a way to emulate AS3's Timer class.
If you're not familiar, one of the cool things you can do is add duration to the timer even if it's already running. This functionality has a lot of very nice uses.
Anyone have any thoughts on doing this in js?
I'm not familiar with this class, but you can easily create something similar in JavaScript:
function Timer(callback, time) {
this.setTimeout(callback, time);
}
Timer.prototype.setTimeout = function(callback, time) {
var self = this;
if(this.timer) {
clearTimeout(this.timer);
}
this.finished = false;
this.callback = callback;
this.time = time;
this.timer = setTimeout(function() {
self.finished = true;
callback();
}, time);
this.start = Date.now();
}
Timer.prototype.add = function(time) {
if(!this.finished) {
// add time to time left
time = this.time - (Date.now() - this.start) + time;
this.setTimeout(this.callback, time);
}
}
Usage:
var timer = new Timer(function() { // init timer with 5 seconds
alert('foo');
}, 5000);
timer.add(2000); // add two seconds
Clear the timeout, then set a new timeout to the new desired end time.
Wrap the function with another one, and when the timer runs out, test to see if an extra time variable has been set. If it has, start again with the new time, otherwise execute the function.
A quickly hacked together script might look like:
function test() {
tim = new timer(function () { alert('hello'); }, 5000);
}
function extend() {
if (tim) { tim.addTime(5000); }
}
function timer(func, time) {
var self = this,
execute = function () {
self.execute()
};
this.func = func;
this.extraTime = 0;
setTimeout(execute, time);
};
timer.prototype.execute = function () {
var self = this,
execute = function () {
self.execute()
};
if (this.extraTime) {
setTimeout(execute, this.extraTime);
this.extraTime = 0;
} else {
this.func();
}
};
timer.prototype.addTime = function (time) {
this.extraTime += time;
}
<input type="button" value="Start" onclick="test()">
<input type="button" value="Extend" onclick="extend()">
There you go hope it helps :) just call setInterval with the time you want to have.
Edit: added stop and start in case you want to stop your loop :p
function Timer(defaultInterval, callback){
var interval = defaultInterval;
var running = true;
function loop(){
callback();
if(running){
setTimeout(function(){
loop();
}, interval);
}
}
loop();
return {
setInterval: function(newInterval){
interval = newInterval;
},
stop: function(){
running = false;
},
start: function(){
if(running===false){
running = true;
loop();
}
},
add: function(milliToAdd){
interval += milliToAdd*1;
}
}
}
var myTimer = Timer(250, function() { process code here });
myTimer.setInterval(1000); // sets interval to 1 second
myTimer.stop(); // stops the function
myTimer.start(); // re-starts the loop;
function Timer(func, delay) {
var done = false;
var callback = function() {
done = true;
return func();
};
var startTime = Date.now();
var timeout = setTimeout(callback, delay);
this.add = function(ms) {
if (!done) {
this.cancel();
delay = delay - (Date.now() - startTime) + ms;
timeout = setTimeout(callback, delay);
}
};
this.cancel = function() {
clearTimeout(timeout);
};
this.immediately = function() {
if (!done) {
this.cancel();
callback();
}
};
};
quick test in the console
start = Date.now();
t = new Timer(function() { console.log(Date.now() - start); }, 1000);
t.add(200);
start = Date.now();
t = new Timer(function() { console.log(Date.now() - start); }, 1000000);
t.immediately();
t.immediately();
you can add negative times too.
start = Date.now();
t = new Timer(function() { console.log(Date.now() - start); }, 1000);
t.add(-200);
Here's my shot. It keeps track of when the timer was set, and adds the difference to the specified time when you add time.
var Timer = {
set: function(p_function, p_time)
{
var d = new Date();
this.timeStarted = d.getTime();
this.func = p_function;
this.timeout = setTimeout(p_function, p_time);
console.log('timer started at ' + (this.timeStarted / 1000) + ' seconds');
},
add: function(p_time)
{
var d = new Date(),
diff = d.getTime() - this.timeStarted,
newTime = diff + p_time;
if (this.timeout)
{
clearTimeout(this.timeout);
}
this.timeout = setTimeout(this.func, newTime);
this.timeStarted = d.getTime();
}
};
var myTimer = Object.create(Timer);
myTimer.set(function() {
var d = new Date();
console.log('Timer fired at ' + (d.getTime() / 1000) + ' seconds');
}, 10000);
setTimeout(function () {
myTimer.add(5000);
}, 5000);
Here's a jsFiddle
Please note that due to overhead of calculation and function calls, this may be a couple milliseconds off.
I decided to throw my little rubber ducky into the pool.
var setTimeout2 = function(callback, delay) {
this.complete = false;
this.callback = callback;
this.delay = delay;
this.timeout = false;
this.dotimeout = function() {
this.timeout = setTimeout(function() {
this.complete = true;
this.callback.call();
}, this.delay);
};
this.start = Date.now();
this.add = function(delay) {
if (!this.complete) {
this.delay = this.delay - (Date.now() - this.start) + delay;
clearTimeout(this.timeout);
this.dotimeout.call();
}
};
return this;
};
usage
var start = Date.now();
var to = setTimeout2(function() {
document.write(Date.now() - start);
}, 3000);
to.add(3000);
similar to this approach but a little more compact / no proto

Categories

Resources