Cant a function be implemented into while loop? - javascript

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);
}
})();
}

Related

How to stop javascript counter at specific number

I have this javascript code for tampermonkey that works on Amazon. What it does is just counts up your gift card balance and makes it look like I am getting money. I want to know if it is possible to make it stop at a specific number.
var oof = document.getElementById("gc-ui-balance-gc-balance-value");
var lastCount = localStorage.getItem("lastCount");
oof.innerText = '$' + lastCount || "$10000";
function animateValue(id) {
var obj = document.getElementById(id);
var current = parseInt(localStorage.getItem("lastCount")) || 10000;
setInterval(function () {
var nextCount = current++;
localStorage.setItem("lastCount", nextCount);
obj.innerText = '$' + nextCount;
}, 0.1);
}
animateValue('gc-ui-balance-gc-balance-value')
Use clearInterval inside your setInterval callback so each time the callback is called, you can check if the new count has reached your threshold and clear the timer if it does.
If you check the value outside of the callback, the logic won't be called at each count increment.
function animateValue(id) {
var obj = document.getElementById(id);
var current = parseInt(localStorage.getItem("lastCount")) || 10000;
var interval = null;
var maxCount = 1000;
var callback = function() {
var nextCount = current++;
if (nextCount === maxCount) {
clearInterval(interval);
}
localStorage.setItem("lastCount", nextCount);
obj.innerText = '$' + nextCount;
}
interval = setInterval(callback, 0.1);
}
Here is a demo:
let current = 0;
let interval = null;
const callback = () => {
let nextCount = current++;
console.log(nextCount);
if (nextCount === 5) {
clearInterval(interval);
}
}
interval = setInterval(callback, 100);
May be by clearing the interval when current reaches to a specific value like this
function animateValue(id) {
// rest of the code
let interval = setInterval(function() {
var nextCount = current++;
localStorage.setItem("lastCount", nextCount);
obj.innerText = '$' + nextCount;
}, 0.1);
if (current === requiredVal) {
clearInterval(interval)
}
return current;
}

timer implementation in javascript

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.

javascript autoreload in infinite loop with time left till next reload

i need a JavaScript, that relaods a page every 30 seconds, and will show how much time there is until next reload at the ID time-to-update, Example:
<p>Refreshing in <span id="time-to-update" class="light-blue"></span> seconds.</p>
i also need it to repeat itself infinitely.
thank you for reading, i hope it helps not me but everyone else, and a real big thank you if you could make this script.
(function() {
var el = document.getElementById('time-to-update');
var count = 30;
setInterval(function() {
count -= 1;
el.innerHTML = count;
if (count == 0) {
location.reload();
}
}, 1000);
})();
A variation that uses setTimeout rather than setInterval, and uses the more cross-browser secure document.location.reload(true);.
var timer = 30;
var el = document.getElementById('time-to-update');
(function loop(el) {
if (timer > 0) {
el.innerHTML = timer;
timer -= 1;
setTimeout(function () { loop(el); }, 1000);
} else {
document.location.reload(true);
}
}(el));
http://jsfiddle.net/zGGEH/1/
var timer = {
interval: null,
seconds: 30,
start: function () {
var self = this,
el = document.getElementById('time-to-update');
el.innerText = this.seconds; // Output initial value
this.interval = setInterval(function () {
self.seconds--;
if (self.seconds == 0)
window.location.reload();
el.innerText = self.seconds;
}, 1000);
},
stop: function () {
window.clearInterval(this.interval)
}
}
timer.start();

How to pause and resume a javascript timer [duplicate]

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

JavaScript countdown timer not starting

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

Categories

Resources