.hide() div when timer reaches 0 - javascript

I have been trying to make a timer disappear when it reaches 00:00 but everytime I try something it just hides the div right away.
Here is the code I am using:
$(document).ready(function(e) {
var $worked = $("#worked");
function update() {
var myTime = $worked.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(0);
dt.setMinutes(ss[0]);
dt.setSeconds(ss[1]);
var dt2 = new Date(dt.valueOf() - 1000);
var temp = dt2.toTimeString().split(" ");
var ts = temp[0].split(":");
$worked.html(ts[1] + ":" + ts[2]);
setTimeout(update, 1000);
}
setTimeout(update, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="worked">00:10</div>

I have created an example for you. For this example I have changed the timer's interval to 10ms so you can see the result quicker. Also instead of setting a setTimeout to run update inside the function update. You can use setInterval. I have also added a check inside the update function that checks if the time is 00:00. If it is true, then it invalidates the interval by calling clearInterval(timer); and runs $worked.hide()
$(document).ready(function (e) {
var $worked = $("#worked");
var timer = setInterval(update, 10);
function update() {
var myTime = $worked.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(0);
dt.setMinutes(ss[0]);
dt.setSeconds(ss[1]);
var dt2 = new Date(dt.valueOf() - 1000);
var temp = dt2.toTimeString().split(" ");
var ts = temp[0].split(":");
$worked.html(ts[1]+":"+ts[2]);
$worked.html(ts[1]+":"+ts[2]);
if(ts[1] === '00' && ts[2] === '00') {
clearInterval(timer);
$worked.hide();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="worked">01:00</div>

Here's another approach :)
$(document).ready(function(e) {
var $worked = $("#timer");
var startTime = new Date().getTime();
var now, currentDistance;
setInterval(function update() {
now = new Date().getTime();
currentDistance = 10000 - now + startTime;
if (currentDistance > 0) {
$worked.html(parseInt(currentDistance / 1000) + " seconds, " + (currentDistance % 1000) + " ms left!");
} else {
$worked.hide();
}
}, 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="timer" style="background-color: rgb(190, 190, 220); width: 200px; text-align: center"></div>

Related

How to make multiple countdown timers at the same page using the codes below?

How to make multiple countdown timers at the same page using the codes below?
I tried to make another countdown timer by making another var start = document.getElementById("start2"); and var dis = document.getElementById("display2"); but when I click the 1 button only the second countdown timer is working,
var start1 = document.getElementById("start1");
var dis1 = document.getElementById("display1");
var finishTime1;
var timerLength1 = 10;
var timeoutID1;
dis1.innerHTML = "" + timerLength1;
if(localStorage.getItem('myTime')){
Update();
}
start1.onclick = function () {
localStorage.setItem('myTime', ((new Date()).getTime() + timerLength1 * 1000));
if (timeoutID1 != undefined) window.clearTimeout(timeoutID1);
Update();
}
function Update() {
finishTime1 = localStorage.getItem('myTime');
var timeLeft = (finishTime1 - new Date());
dis1.innerHTML = "" + Math.max(timeLeft/1000,0)
timeoutID1 = window.setTimeout(Update, 100);
}
var start2 = document.getElementById("start2");
var dis2 = document.getElementById("display2");
var finishTime2;
var timerLength = 100;
var timeoutID;
dis2.innerHTML = "" + timerLength;
if(localStorage.getItem('myTime')){
Update();
}
start2.onclick = function () {
localStorage.setItem('myTime', ((new Date()).getTime() + timerLength * 1000));
if (timeoutID != undefined) window.clearTimeout(timeoutID);
Update();
}
function Update() {
finishTime2 = localStorage.getItem('myTime');
var timeLeft = (finishTime2 - new Date());
dis2.innerHTML = "" + Math.max(timeLeft/1000,0)
timeoutID = window.setTimeout(Update, 100);
}
<span id="display2"></span><button id="start1">START1</button>
<br><br>
<span id="display2"></span><button id="start1">START1</button>
enter code here
You are using the same id for localStorage. Actually it is better to create isolated context through function or class, then it will be easier to handle as much counters as you wish. Also you can use setInterval instead of setTimer
One more tip: when you assign number to string field no need to write "" + value, because number authomatically will be converted into string
const createCounter = (startElementId, displayElementId, localStorageId, timerLength) => {
const startElement = document.getElementById(startElementId),
displayElement = document.getElementById(displayElementId)
let timeoutID
displayElement.innerHTML = timerLength
const storageValue = localStorage.getItem(localStorageId)
if (storageValue) startTimer()
startElement.onclick = () => {
const value = (new Date()).getTime() + timerLength * 1000
localStorage.setItem(localStorageId, value)
startTimer()
}
function startTimer () {
if (timeoutID) clearInterval(timeoutID)
timeoutId = setInterval(updateTime, 100)
}
function updateTime (finishTime) {
finishTime = finishTime || localStorage.getItem(localStorageId)
const timeLeft = finishTime - new Date()
displayElement.innerHTML = Math.max(timeLeft / 1000, 0)
}
}
// run first timer for elements with ids start1 and display1
createCounter('start1', 'display1', 'someId1', 10)
// run second timer for elements with ids start1 and display1
createCounter('start2', 'display2', 'someId2', 60)
html
<button id=start1>Start</button>
<div id=display1></div>
<button id=start2>Start</button>
<div id=display2></div>

Timer and localstorage issue

I am quite new to Javascript and web programming and currently learning localStorage and I have found some code and I tried to modify it. What I am trying to do, when the set time is up, I want to call another function named whatever function.. Please help.
Note: If there is any problem in terms of rule of Stack overflow, Let me know. I will edit & delete the question.
JS
var finishTime;
var timerLength = 10;
var timeoutID;
dis.innerHTML = "Time Left: " + timerLength;
if(localStorage.getItem('myTime')){
Update();
}
$('#save').click(function () {
localStorage.setItem('myTime', ((new Date()).getTime() + timerLength * 1000));
if (timeoutID != undefined) window.clearTimeout(timeoutID);
Update();
});
function Update() {
finishTime = localStorage.getItem('myTime');
var timeLeft = (finishTime - new Date().getTime());
dis.innerHTML = "Time Left: " + Math.max(timeLeft/1000,0);
if(timeLeft <= 0){
console.log('please work');
}else{
timeoutID = window.setTimeout(Update, 100);
}
}
view
<p id="display">Time Left
<p>
<button id="start">Start</button>
didn't try your code but this line:
var timeLeft = (finishTime - new Date());
shouldn't be?
var timeLeft = (finishTime - new Date().getTime());
added the .getTime()
edit:
function Update() {
finishTime = localStorage.getItem('myTime');
var timeLeft = (finishTime - new Date().getTime());
dis.innerHTML = "Time Left: " + Math.max(timeLeft/1000,0);
if (timeLeft <= 0){
localStorage.removeItem('myTime'); //<=remove
whateversomethingfunctuin();
// console.log('Seems');
} else {
//call only when needed
timeoutID = window.setTimeout(Update, 100);
}
}

Issue with countdown timer using javascript or php

I want to run this countdown, but when the countdown finishes, it restarts from 24:00:00. After the countdown finishes, I want to send a message or do something else. How can I do that?
<div id="hms">00:00:02</div>
<script type="text/javascript">
var timeoutHandle;
function count() {
var startTime = document.getElementById('hms').innerHTML;
var pieces = startTime.split(":");
var time = new Date(); time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timedif = new Date(time.valueOf() - 1000);
var newtime = timedif.toTimeString().split(" ")[0];
document.getElementById('hms').innerHTML=newtime;
timeoutHandle=setTimeout(count, 1000);
}
count();
</script>
I have just added a counter variable, and when its zero I am clearing the timeout. Have a look https://jsfiddle.net/koh9ca6j/1/
you can add a condition to check when it reaches to zero either by calculating total seconds or any other method.
var timeoutHandle;
var counter = 5;
function count() {
var startTime = document.getElementById('hms').innerHTML;
var pieces = startTime.split(":");
//console.log(pieces);
var time = new Date();
time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timedif = new Date(time.valueOf() - 1000);
var newtime = timedif.toTimeString().split(" ")[0];
document.getElementById('hms').innerHTML = newtime;
counter--;
if (!counter) {
clearTimeout(timeoutHandle);
return;
}
}
function countdown() {
timeoutHandle = setInterval(count, 1000);
}
countdown()

Timer to be displayed on a webpage

I want to add a count up timer to my webpage, as in, a label that contains 0:00:00 should start displaying 0:00:01 and so on until the stop button is clicked.
Is there a simple javascript/jquery solution to this?
<html>
<head>
<title>Home</title>
<script src="jquery-1.11.1.js">
</script>
<script>
$(document).ready(function(){
$("p").click(function(){
//psst. psst.
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td><input type="text" id="project" placeholder="project"></td>
<td><p id="timer">0:00:00<p></td>
</tr>
</table>
</form>
</body>
</html>
I tried something in Vanilla JS HERE
var seconds=0, minutes=0, hours=0;
var counter;
var stop,start;
var counting = false;
window.onload = function () {
counter = document.getElementById('counter');
stop = document.getElementById('stop');
stop.onclick = function () {
counting = false;
}
start = document.getElementById('start');
start.onclick = function() {
counting = true;
timer();
}
counting = true;
timer();
}
function timer() {
if (seconds >= 60) {
minutes++;
seconds = 0;
}
if (minutes >= 60) {
hours++;
minutes = 0;
}
counter.innerHTML = hours + ":" + minutes + ":" + seconds;
if (counting) {
seconds++;
setTimeout(timer, 1000);
}
}
If you need more info leave a comment..
time.js
function time(id)
{
date = new Date;
h = date.getHours();
if(h<10)
{
h = "0"+h;
}
m = date.getMinutes();
if(m<10)
{
m = "0"+m;
}
s = date.getSeconds();
if(s<10)
{
s = "0"+s;
}
result = h+':'+m+':'+s;
document.getElementById(id).innerHTML = result;
// "setTimeout" call function "time" every 1 second (1000 milliseconds)
setTimeout('time("'+id+'");','1000');
return true;
}
HTML
<html>
<head>
<title>Time in Javascript</title>
<script type="text/javascript" src="time.js"></script>
</head>
<body>
<span id="time"></span>
<script type="text/javascript">window.onload = time('time');</script>
</body>
</html>
Try this way
Use https://github.com/jchavannes/jquery-timer
Include this files in head
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript">
<script src="http://jchavannes.com/include/scripts/3p/jquery.timer.js" type="text/javascript">
Script
var Example1 = new (function() {
var $stopwatch, // Stopwatch element on the page
incrementTime = 70, // Timer speed in milliseconds
currentTime = 0, // Current time in hundredths of a second
updateTimer = function() {
$stopwatch.html(formatTime(currentTime));
currentTime += incrementTime / 10;
},
init = function() {
$stopwatch = $('#stopwatch');
Example1.Timer = $.timer(updateTimer, incrementTime, true);
};
this.resetStopwatch = function() {
currentTime = 0;
this.Timer.stop().once();
};
$(init);
});
function formatTime(time) {
var min = parseInt(time / 6000),
sec = parseInt(time / 100) - (min * 60),
hundredths = pad(time - (sec * 100) - (min * 6000), 2);
return (min > 0 ? pad(min, 2) : "00") + ":" + pad(sec, 2) + ":" + hundredths;
}
function pad(number, length) {
var str = '' + number;
while (str.length < length) {str = '0' + str;}
return str;
}
Example1();
DEMO
By using setInterval and Date
You can use button to stop and start timer.
var d = new Date();
d.setHours(0,0,0,0);
setInterval((function(){
return function(){
d.setSeconds(d.getSeconds()+1);
var t = d.toLocaleTimeString("en-US", {hour12: false});
document.getElementById("demo").innerHTML = t;
}
})(), 1000);
Fiddle Demo
Please try this fiddle for your solution.
JS.
var hour = 0;
var min = 0;
var second = 0;
var i=setInterval(function(){
second++;
if(second > 59){
second = 0;
min++;
if(min>59){
hour++;
min = 0;
}
}
var timer_time = (hour > 9 ? hour : '0'+hour)+':'+(min > 9 ? min : '0'+min)+':'+(second > 9 ? second : '0'+second);
$('#timer').html(timer_time);
}, 1000);
$('#stop_timer').click(function(){
clearInterval(i);
});
HTML
<p id='timer'>00:00:00</p>
<button id='stop_timer'>Stop Timer</button>
Thanks
Use timing events like documented at http://www.w3schools.com/js/js_timing.asp.

Countdown timer for use in several places at same page

I want to make a countdown timer, that can be used on several places in the same page - so I think it should be a function in some way.
I really want it to be made with jQuery, but I cant quite make it happen with my code. I have e.g. 10 products in a page, that I need to make a countdown timer - when the timer is at 0 I need it to hide the product.
My code is:
$(document).ready(function(){
$(".product").each(function(){
$(function(){
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var count = Seconds_Between_dates;
var elm = $(this).attr('id');
alert(elm);
countdown = setInterval(function(){
$(elm + " .time_left").html(count + " seconds remaining!");
if (count == 0) {
$(this).css('display','none');
}
count--;
}, 1000);
});
});
});
EDIT 1:
$(document).ready(function(){
$(".product").each(function(){
var elm = $(this).attr('id');
$(function(){
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var count = Seconds_Between_dates;
alert(elm);
countdown = setInterval(function(){
$(elm + " .time_left").html(count + " seconds remaining!");
if (count == 0) {
$(this).css('display','none');
}
count--;
}, 1000);
});
});
});
Do you have any solutions to this?
I'd probably use a single interval function that checks all the products. Something like this:
$(function() {
/* set when a product should expire.
hardcoded to 5 seconds from now for demonstration
but this could be different for each product. */
$('.product').each(function() {
$(this).data('expires', (new Date()).getTime() + 5000);
});
var countdown_id = setInterval(function() {
var now = (new Date()).getTime();
$('.product').each(function() {
var expires = $(this).data('expires');
if (expires) {
var seconds_remaining = Math.round((expires-now)/1000);
if (seconds_remaining > 0) {
$('.time-left', this).text(seconds_remaining);
}
else {
$(this).hide();
}
}
});
}, 1000);
});
You could also cancel the interval function when there is nothing left to expire.
Your problem seems to be that this doesn't refer to the current DOM element (from the each), but to window - from setTimeout.
Apart from that, you have an unnecessary domReady wrapper, forgot the # on your id selector, should use cached references and never rely on the timing of setInterval, which can be quite drifting. Use this:
$(document).ready(function(){
$(".product").each(function(){
var end = new Date(/* from something */),
toUpdate = $(".time_left", this);
prod = $(this);
countDown();
function countdown() {
var cur = new Date(),
left = end - cur;
if (left <= 0) {
prod.remove(); // or .hide() or whatever
return;
}
var sec = Math.ceil(left / 1000);
toUpdate.text(sec + " seconds remaining!"); // don't use .html()
setTimeout(countdown, left % 1000);
}
});
});

Categories

Resources