This question already has an answer here:
how to pause timer or freeze it and resume -> javascript
(1 answer)
Closed 9 years ago.
I have this timer which works fine, but i need to be able to pause and resume it after that. i would appreciate it if someone could help me.
<html>
<head>
<script>
function startTimer(m,s)
{
document.getElementById('timer').innerHTML= m+":"+s;
if (s==0)
{
if (m == 0)
{
return;
}
else if (m != 0)
{
m = m-1;
s = 60;
}
}
s = s-1;
t=setTimeout(function(){startTimer(m,s)},1000);
}
</script>
</head>
<body>
<button onClick = "startTimer(5,0)">Start</button>
<p id = "timer">00:00</p>
</body>
</html>
I simply can't stand to see setTimeout(...,1000) and expecting it to be exactly 1,000 milliseconds. Newsflash: it's not. In fact, depending on your system it could be anywhere between 992 and 1008, and that difference will add up.
I'm going to show you a pausable timer with delta timing to ensure accuracy. The only way for this to not be accurate is if you change your computer's clock in the middle of it.
function startTimer(seconds, container, oncomplete) {
var startTime, timer, obj, ms = seconds*1000,
display = document.getElementById(container);
obj = {};
obj.resume = function() {
startTime = new Date().getTime();
timer = setInterval(obj.step,250); // adjust this number to affect granularity
// lower numbers are more accurate, but more CPU-expensive
};
obj.pause = function() {
ms = obj.step();
clearInterval(timer);
};
obj.step = function() {
var now = Math.max(0,ms-(new Date().getTime()-startTime)),
m = Math.floor(now/60000), s = Math.floor(now/1000)%60;
s = (s < 10 ? "0" : "")+s;
display.innerHTML = m+":"+s;
if( now == 0) {
clearInterval(timer);
obj.resume = function() {};
if( oncomplete) oncomplete();
}
return now;
};
obj.resume();
return obj;
}
And use this to start/pause/resume:
// start:
var timer = startTimer(5*60, "timer", function() {alert("Done!");});
// pause:
timer.pause();
// resume:
timer.resume();
<p id="timer">00:00</p>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="resume">Resume</button>
var timer = document.getElementById("timer");
var start = document.getElementById("start");
var pause = document.getElementById("pause");
var resume = document.getElementById("resume");
var id;
var value = "00:00";
function startTimer(m, s) {
timer.textContent = m + ":" + s;
if (s == 0) {
if (m == 0) {
return;
} else if (m != 0) {
m = m - 1;
s = 60;
}
}
s = s - 1;
id = setTimeout(function () {
startTimer(m, s)
}, 1000);
}
function pauseTimer() {
value = timer.textContent;
clearTimeout(id);
}
function resumeTimer() {
var t = value.split(":");
startTimer(parseInt(t[0], 10), parseInt(t[1], 10));
}
start.addEventListener("click", function () {
startTimer(5, 0);
}, false);
pause.addEventListener("click", pauseTimer, false);
resume.addEventListener("click", resumeTimer, false);
on jsfiddle
There are a whole load of improvements that could be made but I'm sticking with the code that the OP posted for the OP's comprehension.
Here is an extended version to give you further ideas on jsfiddle
Related
i am trying to code the typed jquery functinality in javascript.I am almost there.HEre i need to add a delay after loading the word.like a few secons(lest say 4 sec) after each word loaded. How can i do it. In tried delay and set time out.It is not working for me or i am placing in wrong position. How can i set it.
var count = 0,
count2 = 0,
arr = ["SWOO", "EXCITE", "WOW", "AMAZE", "IMPRESS", "EDUICATE"],
dir = true;
setInterval(function() {
var interval = setInterval(function() {
document.getElementById('p1').innerHTML = arr[count].substring(0, count2);
if (dir) {
count2++;
if (count2 >= arr[count].length) {
dir = false;
}
} else {
count2--;
if (count2 < 0) {
dir = true;
clearInterval(interval);
}
}
}, 100);
count++;
if (count == 6) count = 0;
}, 2500);
<div style="width=100%">
<span id="p1" className="p2 hero-text-animate"></span> <span>them with video</span>
</div>
Your implementation will have problems if you add “A very long string” in to the array.
I’ve modified your code, hope it will help.
var count = 0,
count2 = 0,
arr = ["SWOO", "EXCITE", "WOW", "AMAZE", "IMPRESS", "EDUICATE"],
dir = true;
var p1 = document.getElementById("p1");
// Turning the intervals to on or off.
var onOff = function(bool, func, time) {
if (bool === true) {
interval = setInterval(func, time);
} else {
clearInterval(interval);
}
};
var eraseCharacters = function() {
// How long we want to wait before typing.
var wait = 1000;
// How fast we want to erase.
var erasingSpeed = 100;
var erase = function() {
p1.innerHTML = arr[count].substring(0, count2);
count2--;
if (count2 < 0) {
dir = true;
// Stop erasing.
onOff(false);
count++;
if (count === 6) {
count = 0;
}
// Start typing.
setTimeout(startTyping, wait);
}
};
// Start erasing.
onOff(true, erase, erasingSpeed);
};
var startTyping = function() {
// How long we want to wait before erasing.
var wait = 4000;
// How fast we want to type.
var typingSpeed = 100;
var type = function() {
p1.innerHTML = arr[count].substring(0, count2);
if (dir) {
count2++;
if (count2 > arr[count].length) {
dir = false;
// Stop typing.
onOff(false);
// Start erasing.
setTimeout(eraseCharacters, wait);
}
}
};
// Start typing.
onOff(true, type, typingSpeed);
};
// Start typing after 2 seconds.
setTimeout(startTyping, 2000);
<div style="width=100%">
<!-- Maybe it should be class. -->
<span id="p1" className="p2 hero-text-animate"></span> <span>them with video</span>
</div>
I had written following code for implementing a timer in JS. But the issue is, for the subsequent recursive calls, the method throws reference error for timeChkSplitTime. How does it happen as its being passed in settimeout().
Also, later I used the easy timer js lib for this. If possible, pls provide an idea to configure the timer for minutes and seconds alone.
function timeChkold(timeChkSplitTime) {
var min = timeChkSplitTime[0], sec = timeChkSplitTime[1];
if (!(timeChkSplitTime[0]==0 && splitTime[1]==0)) {
var strSec, strMin = "0"+min.toString();
if (sec < 10) strSec = "0"+ sec.toString();
else strSec = sec.toString();
$(".timer-btn time").html(strMin+":"+strSec);
timeChkSplitTime[0]=0;
if (sec > 0) timeChkSplitTime[1]--;
else timeChkSplitTime[1] = 59;
setTimeout( "timeChk(timeChkSplitTime);", 1000);
}
else {
var startBtn = $(".start-btn");
startBtn.html("Start");
startBtn.css( {
"border": "1px solid #56B68B",
"background": "#56B68B",
});
var startTime = "01:00";
$(".timer-btn time").html(startTime);
}
}
setTimeout( "timeChk(timeChkSplitTime);", 1000);
should be
setTimeout( timeChk(timeChkSplitTime), 1000);
Variables aren't parsed through strings, on the line with the code:
setTimeout( "timeChk(timeChkSplitTime);", 1000);
It's literally reading the parameter as the value as the text timeChkSplitTime and not the value of the variable timeChkSplitTime. Other than using a string use a function for setTimeout:
setTimeout( timeChk(timeChkSplitTime), 1000);
your code is a little bit of a spaghetti code. you should seperate your code logic from the view. split them into functions. and most importantly, using setTimeout is not efficient in this case.
var CountdownTimer = function(startTime) {
var timeInSeconds = this.stringToSeconds(startTime);
this.original = timeInSeconds;
this.time = timeInSeconds;
this.running = false;
}
CountdownTimer.prototype.start = function(callback) {
this.running = true;
this.interval = setInterval(function() {
if(this.time < 1) {
this.running = false;
clearInterval(this.interval);
} else {
this.time -= 1;
callback();
}
}.bind(this), 1000);
}
CountdownTimer.prototype.pause = function() {
if(this.running) {
this.running = false;
clearInterval(this.interval);
}
}
CountdownTimer.prototype.restart = function() {
this.time = this.original;
}
CountdownTimer.prototype.stringToSeconds = function(timeSting) {
var timeArray = timeSting.split(':');
var minutes = parseInt(timeArray[0], 10);
var seconds = parseInt(timeArray[1], 10);
var totalSeconds = (minutes*60) + seconds;
return totalSeconds;
}
CountdownTimer.prototype.secondsToStrings = function(timeNumber) {
finalString = '';
var minutes = parseInt(timeNumber/60, 10);
var seconds = timeNumber - (minutes*60);
var minStr = String(minutes);
var secStr = String(seconds);
if(minutes < 10) minStr = "0" + minStr;
if(seconds < 10) secStr = "0" + secStr;
return minStr + ":" + secStr;
}
to run this code you can add the following
var countdownTest = new CountdownTimer("01:15");
countdownTest.start(onEachTick);
function onEachTick() {
var time = countdownTest.secondsToStrings(countdownTest.time);
console.log(time)
}
you can write your custom code in the onEachTick funciton.
you can check if the timer is running by typing countdownTest.running.
you can also restart and pause the timer. now you can customize your views however you want.
I cant figuret how set cookie for my countdownt timeer, that if i refresh page it vill not disapear but vill counting.
i be glad if eny can help. i use jquery 2.1.4 and this java countdown script, but when i refresh page all my coundown timers are lost!
/**
* Created by op on 18.07.2015.
*/
function leadZero (n)
{
n = parseInt(n);
return (n < 10 ? '0' : '') + n;
}
function startTimer(timer_id) {
var timer = $(timer_id);
var time = timer.html();
var arr = time.split(":");
var h = arr[0];
h = h.split(" / ");
h = h[1];
var m = arr[1];
var s = arr[2];
if (s == 0)
{
if (m == 0)
{
if (h == 0)
{
timer.html('')
return;
}
h--;
m = 60;
}
m--;
s = 59;
}
else
{
s--;
}
timer.html(' / '+leadZero(h)+":"+leadZero(m)+":"+leadZero(s));
setTimeout(function(){startTimer(timer_id)}, 1000);
}
function timer (name, time)
{
var timer_name = name;
var timer = $(timer_name);
var time_left = time;
timer.html(' / '+ time);
startTimer(timer_name);
}
$(document).ready(function(){
$('.fid').click(function (e)
{
var timer_name = '.timer_'+$(this).data('fid');
var timer = $(timer_name);
if (timer.html() == '')
{
var time_left = timer.data('timer');
var hours = leadZero(Math.floor(time_left / 60));
var minutes = leadZero(time_left % 60);
var seconds = '00';
timer.html(' / '+hours+':'+minutes+':'+seconds);
startTimer(timer_name);
}
});
$.each($('.tab'), function () {
$(this).click(function () {
$.each($('.tab'), function() {
$(this).removeClass('active');
});
$(this).addClass('active');
$('.list').hide();
$('#content-'+$(this).attr('id')).show();
});
});
if (window.location.hash != '')
{
var tab = window.location.hash.split('-');
tab = tab[0];
$(tab).click();
}
console.log(window.location.hash)
});
It would help if you actually set a cookie.
Setting the cookie would go like:
document.cookie="timer=" + time;
And then call it at the beginning of your code
var time = getCookie("timer");
The getCookie() function is outlined in that link, as well as a base knowledge about them.
function start() {
var work = document.getElementById("work").value;
var rest = document.getElementById("rest").value;
var rounds = document.getElementById("rounds");
var timer = document.getElementById("timer");
function countdown() {
var roundsValue = rounds.value;
while (roundsValue > 0) {
var worktime = setInterval(function () {
timer.value = work + "sec";
work = work - 1;
if (work === 0) {
clearInterval(worktime);
}
}, 1000);
var resttime = setInterval(function(){
timer.value = rest + "sec";
rest = rest-1;
if(rest === 0){
clearInterval(resttime);
}
}, 1000);
roundsValue = roundsValue-1;
}
}
}
I am working on my javascript progress right now and I came here with this problem. I want to repeat the same amount of work time and rest time as rounds are but it doesnt work like this and I cant help myself. For example: 8 rounds of 10 seconds of work and then 5seconds of rest. It maybe doesnt work because function cant be implemented into a WHILE loop.
fiddle: http://jsfiddle.net/shhyq02e/4/
Here is a quick fix, may not be the best way to go about it but will get what to do.
http://jsfiddle.net/sahilbatla/shhyq02e/6/
function start() {
var rounds = document.getElementById("rounds");
var timer = document.getElementById("timer");
var roundsValue = parseInt(rounds.value);
(function countdown() {
var work = document.getElementById("work").value;
var rest = document.getElementById("rest").value;
if (roundsValue > 0) {
var worktime = setInterval(function () {
timer.value = work + "sec(work)";
work = work - 1;
if (work === 0) {
clearInterval(worktime);
var resttime = setInterval(function() {
timer.value = rest + "sec(rest)";
rest = rest - 1;
if (rest === 0) {
clearInterval(resttime);
--roundsValue;
countdown();
}
}, 1000);
}
}, 1000);
}
})();
}
I tried using this JavaScript countdown timer on my page but the timer won't start.
What am I doing wrongly?
var CountdownID = null;
var start_msecond = 9;
var start_sec = 120;
window.onload = countDown(start_msecond, start_sec, "timerID");
function countDown(pmsecond, psecond, timerID) {
var msecond = ((pmsecond < 1) ? "" : "") + pmsecond;
var second = ((psecond < 9) ? "0": "") + psecond;
document.getElementById(timerID).innerHTML = second + "." + msecond;
if (pmsecond == 0 && (psecond-1) < 0) { //Recurse timer
clearTimeout(CountdownID);
var command = "countDown("+start_msecond+", "+start_sec+", '"+timerID+"')";
CountdownID = window.setTimeout(command, 100);
alert("Time is Up! Enter your PIN now to subscribe!");
}
else { //Decrease time by one second
--pmsecond;
if (pmsecond == 0) {
pmsecond=start_msecond;
--psecond;
}
if (psecond == 0) {
psecond=start_sec;
}
var command = "countDown("+pmsecond+", "+psecond+", '"+timerID+"')";
CountdownID = window.setTimeout(command, 100);
}
}
<span style="color:red" name="timerID" id="timerID">91.6</span>
here is what you need to do first
window.onload = countDown(start_msecond, start_sec, "timerID");
should be
window.onload = function () {
countDown(start_msecond, start_sec, "timerID");
}
also you should avoid using a string in your setTimeout function:
CountdownID = window.setTimeout(function () {
countDown(pmsecond,psecond,"timerID");
}, 100);
See here http://jsbin.com/ifiyad/2/edit