Resume timer after clearInterval() - javascript

The clearInterval function only stops the timer in my code, but not the actual time. After I click the stop button, the timer stops, but it seems like it is still running in the background. When I re-click the start button again, it does not resume from where it stop, but show me the actual time that has been running in the background. Please see the action in the code.
How can I really stop the timer and resume it after I click on the stop button by clicking on the start button again?
var timeBegan = new Date();
function start(){
started = window.setInterval(clockRunning, 10);
}
function stop(){
window.clearInterval(started);
}
function clockRunning(){
currentTime = new Date()
, timeElapsed = new Date(currentTime - timeBegan)
, hour = timeElapsed.getUTCHours()
, min = timeElapsed.getUTCMinutes()
, sec = timeElapsed.getUTCSeconds()
, ms = timeElapsed.getUTCMilliseconds();
document.getElementById("display-area").innerHTML =
(hour > 9 ? hour : "0" + hour) + ":" +
(min > 9 ? min : "0" + min) + ":" +
(sec > 9 ? sec : "0" + sec) + "." +
(ms > 99 ? ms : ms > 9 ? "0" + ms : "00" + ms);
};
function reset(){
window.clearInterval(started);
running = 0;
hour = min = sec = ms = 0;
document.getElementById("display-area").innerHTML = "00:00:00.000";
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Stopwatch</title>
<script src="stopwatch.js"></script>
<style>
#display-area { font-size: 20pt; }
</style>
</head>
<body>
<div>
<output id="display-area">00:00:00.000</output>
</div>
<div>
<button id="start-button" onClick="start()">Start</button>
<button id="stop-button" onclick="stop()">Stop</button>
<button id="reset-button" onclick="reset()">Reset</button>
</div>
</body>
</html>

This is because you never reset timeBegan. You are continuing to use the same value for the start time.
You need to set this value to the current time within start(), otherwise you are just using the time the page loaded as your reference time instead of the time that start() was last invoked.
var timeBegan;
function start() {
timeBegan = new Date();
started = window.setInterval(clockRunning, 10);
}
Alternatively, you can do this within reset(), and then a stop click followed by a start click will act more like a lap timer; you can freeze the time, but in the background it would keep counting until you click the reset button.
If you want the stop button to pause the timer, then at the moment you click stop you need to record the current duration somewhere. Then in your clockRunning() function you would add this duration to whatever your time subtraction calculation yields. (And, of course, reset() should clear out this stored duration.)

Instead of your current implementation of timeElapsed, what you would want is to make timeElapsed a sum counter where for every call of clockRunning, you would add the time difference from the last clockRunning call to timeElapsed.
start should start/resume clockRunning function calls
clockRunning should add to timeElapsed the time difference from the last clockRunning call
stop should stop clockRunning function calls, and set the clockRunning call time to something like null or -1.
In start, if the last time clockRunning is called is null or -1 (basically, if stop was called), set the last time clockRunning is called to now.

Related

How to create a simple countdown timer in JS?

I have very little experience in coding in general, however, I still need a timer that comes on a pop-up that goes from 20 or 30 minutes to 0, and it should display the time remaining (like MM:SS). Then, when the timer hits 0, a new pop-up should appear that displays some plain text. Is this even possible?
This could do the work
let time = 5;
let element = document.getElementById('countdown');
function lower() {
if(time >= 0) {
element.innerHTML = time--;
}
else {
console.log('popup')
//open popup here
}
}
setInterval(lower, 1000);
I did not do the time format tho. Only shows in seconds now

Body Background based on hour of the day JS

<script type="javascript">
jQuery(document).ready(function($){
var dt = new Date();
var currentHour = dt.getHours();
$('body').css('background', '#FFF url(https://crystalforums.cf/bk/bk_'+currentHour+'.png) no-repeat center center fixed');
$('body').css('background-size', 'cover');
});
</script>
Hey! I had this script working on a my forum and i tried working it on a my website index, but it seems to not work. They both use the body thingy (I forgot the actual term, it's Saturday and i got a ton of work) so they should effect the body element right? What am i doing wrong, the script suppose to set the background image of the website to a new image based on every hour. Help???
I don't want it to auto update, they cxan refresh. I want so there is one background for every hour.
First...I don't recommend use javascript for this....Your approach needs an user for an hour into your website and in the same page...If you still think in change that you will need use setTimeout function...
My recommendation is using a server side technology for this...
You can use setInterval() with duration set to 5 minutes 60000 * 5 or briefer duration between function calls
$().ready(function() {
var interval, curr;
function handleBackground() {
var dt = new Date();
var currentHour = dt.getHours();
if (!curr || currentHour !== curr) {
curr = currentHour;
$('body').css('background', 'url(https://crystalforums.cf/bk/bk_'
+ currentHour
+ '.png) no-repeat center center fixed');
}
}
// call `handleBackground` to set initial `background` at `body`
handleBackground();
interval = setInterval(handleBackground, 60000 * 5);
});
plnkr http://plnkr.co/edit/5YTPgPgaKbXfYIT0MG3x?p=preview
I don't know JQuery, I always use Java Script :P,
If you want to change background after 5 Minutes you can do this by javascript
<script>
index = 0;
function changeBackground(){
var backColor = ["image.jpg","image2.jpg","image3.jpg","image4.jpg"];
document.body.style.backgroundImage = "url("+backColor[index]+")";
index++;
if(index > (backColor.length) - 1){
index = 0;
}
}
//1000 means 1 second, so for 5 min
// 6,000 X 5 = 30,000
setInterval(changeBackground, 30000);
</script>
Just try this code.
You can use the setInterval() function like this:
function someFunction() {
alert("It's been one hour");
}
setInterval(someFunction, 3600000);
Where the 3600000 is a hour in milliseconds.

Track total time taken for a task

I am building a site where task is assigned to each user and he/she needs to complete the task within a fixed duration of time.
For this is need to track Time taken on each task. I also need to track if the user is sitting idle on the site.
Right now i can do this using this code :
HTML
<a class="btn btn-success btn-lg" id="startTracking" role="button">Start Tracking</a>
<a class="btn btn-danger btn-lg" id="endTracking" role="button">Stop Tracking</a>
<h2 id="testingSince"></h2>
JAVASCRIPT
<script type="text/JavaScript">
var totalSeconds = 0;
var idleSeconds = 0;
$(document).ready(function () {
$('body').on('click','#startTracking',function(){
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 1000); // 1 second
});
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleSeconds = 0;
});
$(this).keypress(function (e) {
idleSeconds = 0;
});
});
function timerIncrement() {
totalSeconds += 1;
idleSeconds += 1 ;
if (idleSeconds > 600) { // 20 minutes
alert('You have been sitting Idle for 10 Minutes');
}
$('#testingSince').text(timeStringfromSeconds(totalSeconds));
}
function timeStringfromSeconds(totalSeconds){
var hours = Math.floor(totalSeconds / 36e2),
mins = Math.floor((totalSeconds % 36e2) / 60),
secs = Math.floor((totalSeconds % 60));
return ("0" + hours).slice(-2)+':'+("0" + mins).slice(-2)+':'+("0" + secs).slice(-2);
}
</script>
So this code works great and the user can see the time spent since he clicked the button. It also tracks user idle time and gives an alert after 10 minutes.
However the only Problem here is that when the page reloads the counter starts from 0. i.e the 2 lines :
var totalSeconds = 0;
var idleSeconds = 0;
I just want the timer counter not to restart and continue from its previous value.
One way of doing this is using Cookies. So i have to update them every second but i am not sure if this is a good Idea.
Please let me know if there is any other way or i need to use browser cookies ?
Many users will not permit cookies on their computers. You should never rely only on cookies. Maybe you should make some script that you can ajax call every second or two or five and store elapsed time in session.

Setting and resetting the countdown in every page Jquery

Trying to implement a count down timer, so once I navigate to each screen the timer should reset.
So for each every minute the timer should automatically initialize and starts the count down from 10 to 0.
If user interupts in the middle of count down it should be in the same page, else it should navigate to home page.
This is what I have tried. My timer is calling only once and how do I know that the page has been changed and reset the timer to calulate from 1 minute.
JS:
$(document).ready(function() {
// Function to update counters on all elements with class counter
var doUpdate = function() {
$('.countdown').each(function() {
var count = parseInt($(this).html());
if (count !== 0) {
$(this).html(count - 1);
}
});
};
// Schedule the update to happen once every second
setInterval(doUpdate, 1000);
});
HTML:
<div class="countdown">10</div>
Once you have reached 0 on your countdown you could clear your current intervals using clearInterval() and restart the whole process after a minute. You could have another setInterval() which does this every minute.
Here is a fiddle which resets counters every 12 seconds: http://jsfiddle.net/uo7jLf4b/1/

Popup box with a timer

After some specified inactivity time (IDLE Time say for 10 mins) the application should give a pop up box with a timer (should display like 60 59 58 ....1), that box should close within 60 secs with cancel option selected and that browser should close if user doesn't select any option. If the user selects the cancel option within 60 secs also it should be closed.
To show a popup box I am using setTimeout("pop()",600000); but how to include a timer in that at least that box should close within 60 sec if user doesn't select any option. Is there a solution for this?
You may try putting below code in your popup window.
<script>
function mytimer()
{
setTimeout(function closewin(){window.close;}, 600000);
}
</script>
<body onload="mytimer();">
You can use setTimeout() or setInterval() again. In your pop() function, start another function with a timeout of 1 second (1000ms) and on each call decrease a counter and update the label. When the counter reaches 0, check that the box is still on the screen and if so call window.close() (not all browsers will actually respond to a closing attempt though).
Example:
function pop() {
var counter = 60;
var box = document.createElement('div');
var label = document.createElement('span');
label.innerText = counter;
box.appendChild(label);
// Position box and label as you wish.
function tick() {
counter--;
if (counter == 0) {
window.close();
} else {
label.innerText = counter;
setTimeout(tick, 1000);
}
}
setTimeout(tick, 1000);
}

Categories

Resources