increment value of a number with a specific timer-value - javascript

I've tried and looked around but I could not find anything similar.
<div> <span>23</span>/ 30 </div>
My thought process here is that I want 23 to increment in 1 value every 15th second.
And when it hits 30, it shall stop counting. I have no idea how to make it "stop" counting and how I should approach a problem like this.
Any help would be much appreciated!

Here is a possible solution, note that I do an iteration every second for the demo, but you can lower the rate by doing setTimeout(count,15000);.
var wrapper, value, timer;
window.addEventListener('load', startCounter, false);
function startCounter(){
document.querySelector('button').onclick = startCounter;
wrapper = document.querySelector('span');
value = 22;
count();
}
function count(){
clearTimeout(timer);
value++;
wrapper.innerHTML = value;
if(value < 30){ timer = setTimeout(count,1000); }
}
<div> <span>23</span>/ 30 </div>
<button>reset</button>

<div id="show"></div>
<script>
function timer(){
var i = 0;
setInterval(function(){
i++;
document.getElementById("show").innerHTML = i;
if(i > 30){
i = 0;
}
},1000);
}
timer();
</script>
//just super simple hope can be inspiration done thank

If a class is added to the span element like so:
<div> <span class="counter">23</span>/ 30 </div>
Then this javascript code would work:
var currentCount = parseInt($('.counter').text());
var increaseCount = function() {
if (currentCount < 30) {
currentCount = currentCount + 1;
$('.counter').text(currentCount);
setTimeout(increaseCount, 15000);
}
return;
};
setTimeout(increaseCount, 15000);
Here is an example with the timer set to a second:
https://jsfiddle.net/aqe43oLa/1/

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var i = 24;
var timer=setInterval( increment, 15000);
function increment(){
if(i<=30)
{
console.log(i);
$('.increase').html('').append(i);
i++;
}
else
{
clearInterval(timer);
}
}
</script>
</head>
<body>
<div><span class="increase">23</span>/ 30 </div>
</body>
</html>

Related

I created a Stopwatch in JavaScript. I would like to add a sound when a user inputs the time to be reminded

I am a newbie and trying to learn. I created a Start-stop watch in HTML and js. I would like to add an input field for the users to input time and when it hits that a sound should be played.
I tried to make a variable and try to get the input data but I only screw up everything. I tried to look for it on YouTube and Google but I couldn't seem to find any answers.
Thanks for your time. Below is my code.
<div class="controls">
<button onclick="start()">Start</button>
<button onclick="pause()">Pause</button>
<button onclick="stop()">Stop</button>
<button onclick="restart()">Restart</button>
<button onclick="lap()">Lap</button>
<button onclick="resetLaps()">Reset Laps</button>
</div>
<div class="stopwatch">
00:00:00
</div>
<input type="text" id="inputVal"><button onclick="getVal()">Set Time</button>
<ul class="laps"></ul>
<audio id="ado" src="http://static1.grsites.com/archive/sounds/musical/musical009.mp3" controls="true"></audio>
Below is the Javascript.
<script type="text/javascript">
var ms = 0, s = 0, m = 0;
var timer;
var stopwatchEL = document.querySelector('.stopwatch');
var lapsContainer = document.querySelector('.laps');
function start(){
if(!timer){
timer = setInterval(run, 10)
}
}
function run(){
stopwatchEL.textContent = getTimer();
ms++;
updateTimer();
if(ms == 100){
ms = 00;
s++
}
if(s == 60){
s = 0;
m++;
}
}
function pause(){
stopTimer();
}
function stop(){
stopTimer();
m = 0;
ms = 0;
s = 0;
stopwatchEL.textContent = getTimer();
}
function getTimer(){
return (m < 10 ? "0" + m:m) + ":" + (s < 10 ? "0" + s:s) + ":" + (ms < 10 ? "0" + ms:ms);
}
function stopTimer(){
clearInterval(timer);
timer = false;
}
function restart(){
stop();
start();
}
function lap(){
if(timer){
var li = document.createElement('li');
li.innerText = getTimer();
lapsContainer.appendChild(li);
}
}
function resetLaps() {
lapsContainer.innerHTML = "";
}
function getVal(){
var inputVal = document.getElementById('inputVal').value;
}
function updateTimer() {
if(m == 0, ms == 0, s == inputVal){
$('#ado').get(0).play();
pause();
}
}
</script>
Thanks again.
First you need inputVal globally as #Denhell mentioned.
var inputVal = Number.POSITIVE_INFINITY;
function getVal(){
inputVal = document.getElementById('inputVal').value;
}
Second your function updateTimer needs a comparison between your inputVal and the actual time of the timer. For playing the sound I transferred your jQuery-code to vanilla JS.
function updateTimer() {
if(getTimer() == inputVal){
document.getElementById('ado').play();
pause();
}
}
In the function run the call of the updateTimer has to be executed at the end because otherwise the value for the comparison doesn't function right at the beginning of a new second or minute (e.g. 00:13:00).
function run(){
stopwatchEL.textContent = getTimer();
ms++;
if(ms == 100){
ms = 0;
s++;
}
if(s == 60){
s = 0;
m++;
}
updateTimer();
}
The only thing is, that the timer stops right but do not update the last ms. For this you could look yourself. For my solution it is necessary that the manually set time is at the format mm:ss:ms with all three values as a 2-digit value like 01:17:09
You can try it here: https://jsfiddle.net/8w67uy5a/5/
You are declaring a variable inputVal inside a getVal function that other functions don't know about it.
Use something like this
var inputVal = Number.POSITIVE_INFINITY;
function getVal(){
inputVal = document.getElementById('inputVal').value;
}
This will fix your problem.
<audio id="ado">
<source src="http://static1.grsites.com/archive/sounds/musical/musical009.mp3" type="audio/mpeg"></source>
</audio>
function getVal() {
const sound = document.getElementById("ado");
sound.play();
var inputVal = document.getElementById("inputVal").value;
}

setInterval not updating with variable

When I run the code it only intervals at the initial variable I created "2000". When i click on the button it doesn't change the interval to "50". Does anyone know why?
<html>
<body>
<h1 id="pressme"> Press me! </h1>
</body>
<script>
amount = 2000;
var i = 1;
document.getElementById("pressme").onclick = function() {
amount = 50;
}
function doSomething() {
i++;
console.log("I did something! " + i);
}
setInterval(doSomething, amount)
</script>
</html>
This isn't the OG code, more a simplified version of it.
You should use setInterval with clearInterval together.
<html>
<body>
<h1 id="pressme"> Press me! </h1>
</body>
<script>
amount = 2000;
var i = 1;
var handler
document.getElementById("pressme").onclick = function() {
amount = 50;
clearInterval(handler);
handler = setInterval(doSomething, amount);
}
function doSomething() {
i++;
console.log("I did something! " + i);
}
handler = setInterval(doSomething, amount);
</script>
So when click button, you should remove original setInterval handler and recreate it.
The interval was already set with the 2s, if you change the variable after that, it won't make any difference.
I recommend you do this:
let amount = 2000;
let interval = setInterval(doSomething, amount);
var i = 1;
document.getElementById("pressme").onclick = function () {
clearInterval(interval);
amount = 50;
setInterval(doSomething, amount);
}
function doSomething() {
i++;
console.log("I did something! " + i);
}

Confused about SetInterval and closures

How can we repeatedly update the contents of a div using setInterval
I am using the question from this link as a reference How to repeatedly update the contents of a <div> by only using JavaScript?
but i have got few questions here
Can we do it without anonymous functions,using closures. I have tried but could not end up with any workable solution.
How can we make it run infinitely, with the following code it gets stopped once i reaches 10.
window.onload = function() {
var timing = document.getElementById("timer");
var i = 0;
var interval = setInterval(function() {
timing.innerHTML = i++;
if (i > 10) {
clearInterval(interval);
i = 0;
return;
}
}, 1000);
}
<div id="timer"></div>
I am confused about setIntervals and closures
can some one help me here
Thanks
You could do something like this with a closure. Just reset your i value so, you will always be within your given range.
window.onload = function() {
var updateContent = (function(idx) {
return function() {
if (idx === 10) {
idx = 0;
}
var timing = document.getElementById("timer");
timing.innerHTML = idx++;
}
})(0);
var interval = setInterval(updateContent, 1000);
}
<div id="timer"></div>
This one should be clearer.
function updateTimer() {
var timer = document.getElementById("timer");
var timerValue = parseInt(timer.getAttribute("data-timer-value")) + 1;
if (timerValue == 10) {
timerValue = 0;
}
timer.setAttribute("data-timer-value", timerValue);
timer.innerHTML = "the time is " + timerValue;
}
window.onload = function() {
setInterval(updateTimer, 1000);
}
<div id="timer" data-timer-value="0"></div>

How to stop timer after ten seconds in javascript using setInterval and clearInterval?

I was wondering how can I stop a timer after ten seconds in javascript using setInterval and clearInterval??
Here's my code example, could you please tell me where I'm going wrong:
<!DOCTYPE html>
<html>
<head>
<script>
var tt=setInterval(function(){startTime()},1000);
function startTime()
{
var today = new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
today=checkTime(today);
document.getElementById('txt').innerHTML=s;
}
function checkTime(tt)
{
if (tt==10)
{
tt="0" + tt;
console.log(tt);
clearInterval(tt);
}
return tt;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
you can set timeout on clear like this right after you set the interval:
var tt = setInterval(function(){ startTime() }, 1000);
setTimeout(function() { clearInterval(tt); }, 10000);
Since startTime() will run every second, make a counter to increment to 10 inside of it, then clear the interval.
var tt=setInterval(function(){startTime()},1000);
var counter = 1;
function startTime()
{
if(counter == 10) {
clearInterval(tt);
} else {
counter++;
}
document.getElementById('txt').innerHTML= counter;
}
JSFiddle
Because you named a local variable named tt which does not let you access the global variable tt. Very bad planning on variable names.
Your code also will not stop at 10 seconds, it will stop when the time is at 10 seconds or 10 minutes.
function checkTime(xtt)
{
if (xtt==10)
{
xtt="0" + xtt;
console.log(xtt);
clearInterval(tt);
}
return xtt;
}
This works for me.
var tt = setInterval(function(){ startTime() }, 1000);
setTimeout(function() { clearInterval(tt); }, 10000);
you can do that
setInterval(startTime, 1000).pipe(takeUntil(timer(10000)));

show div after click and start timer

want to show a div after click on a button and then the time start and count from 10 to 0 .
my probelm is i don't know how to start count ?
javascript :
<script>
$("button").click(function() {
$('div#test').hide().delay(200).fadeIn('slow');
});
</script>
button :
<div id="test" style="display:none;">click</div>
html :
<div id="test" style="display:none;">here you are !</div>
You can use setInterval for counting.
var count = 10;
var temp = setInterval(function(){
if(count < 0) {
clearInterval(temp);
}
// show count
count--;
}, 1000);
You can use either setTimeout() or setInterval() to get it working:
Below is how I did it:
$(function() {
$("button").click(function() {
function counter() {
var i = 10;
$("body").append('<div style="border:1px solid red;">Div Created on the Fly</div>')
function showDIV() {
if (i < 0)
return
setTimeout(showDIV, 1000);
$("span").text(i);
i--;
}
showDIV();
}
counter(10);
});
});
DEMO
var count = 15;
var timerID = 0;
$("button").click(function() {
$('div#test').hide().delay(200).fadeIn('slow', function() {
timerID = setInterval(function() {countDown();}, 1000); // count every 1000 ms, change this to whatever you want
});
$("#wait").show(); // or you could fade this in if you want. Maybe that's what you intended with #test.
});
function countDown() {
count--;
$("#count").text(count);
// do whatever you want to do with your count
if (count <= 0) {
clearInterval(timerID);
}
}
HTML:
<p id="wait" style="display:none">Please wait<span id="count">15</span> seconds...</p>
Assuming you wanted to start the count down after the fadeIn. Otherwise, just pull that piece out and setInterval after the fadeIn line which will start the countdown when the button is first clicked.

Categories

Resources