decrementing timer on user input - javascript

I am trying to set a decrementing timer when a user inputs something in an input. However, I am struggling to get it to properly work, when a user writes something new it restarts.
I thought .one would take care of this but apparently not.
function myTimer() {
var counter = 15;
var x = window.setInterval(function() {
counter--;
if (counter >= 0) {
span = document.getElementById("timer");
span.innerHTML = counter;
}
if (counter === 0) {
span.innerHTML = "OUT OF TIME";
window.clearInterval(x);
}
}, 1000);
}
$("#wrapper input").one("change paste keyup", myTimer);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="timer">15</span><br>
<div id="wrapper">
<input class="something" type="text"><br>
<input class="somethingelse" type="text">
</div>
jsFiddle

Move the counter and test the tId:
var counter = 15, x, span = document.getElementById("timer");
function myTimer() {
if (!x) x = window.setInterval(function() {
if (counter === 0) window.clearInterval(x);
counter--;
span.innerHTML = counter >= 0 ? counter : "OUT OF TIME"
}, 1000);
}
$("#wrapper input").one("change paste keyup", myTimer);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="timer">15</span><br>
<div id="wrapper">
<input class="something" type="text"><br>
<input class="somethingelse" type="text">
</div>

You need a global bool variable isCounterRunning. On first line of your function check its value, if it's true return out the function before doing anything, and if it's false, set it to true and then do the rest of the code in your function.
var isCounterOn = false
function myTimer() {
if(isCounterOn) return;
else{
isCounterOn = true
var counter = 15;
var x = window.setInterval(function() {
counter--;
if (counter >= 0) {
span = document.getElementById("timer");
span.innerHTML = counter;
}
if (counter === 0) {
span.innerHTML = "OUT OF TIME";
window.clearInterval(x);
}
}, 1000);
}
}
$("#wrapper input").one("change paste keyup", myTimer);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="timer">15</span><br>
<div id="wrapper">
<input class="something" type="text"><br>
<input class="somethingelse" type="text">
</div>

you have to initialize x outside startInterval so it can be overwritten subsequentially. Moreover, one() will do, as the name says, only one event trigger. If you want to catch everytime an event happens, use on()
var counter = 15;
var x = 0;
var span = document.getElementById("timer");
function myTimer() {
window.clearInterval(x);
startInterval();
}
function startInterval() {
counter = 15;
span.innerHTML = counter;
x = setInterval(function() {
counter--;
if (counter >= 0) {
span.innerHTML = counter;
}
if (counter === 0) {
span.innerHTML = "OUT OF TIME";
window.clearInterval(x);
}
}, 1000);
}
$("#wrapper input").on("change paste keyup", myTimer);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="timer">15</span><br>
<div id="wrapper">
<input class="something" type="text"><br>
<input class="somethingelse" type="text">
</div>

Related

Jquery change event on textbox

Basically, I want to change value on, say textbox2, when the value of textbox1 is changed by a button function. I know that it is possible to include the function on the button to change the value on the textbox2, but I don't want that. Is it possible?
Here's what I tried so far on JSFiddle https://jsfiddle.net/xpvt214o/387300/
HTML code:
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" readonly/>
<input type="text" id="outputtext2" value="" />
JavaScript:
jQuery('#button1').on('click', function() {
document.getElementById("outputtext1").value = parseInt(document.getElementById("outputtext1").value) +1;
});
jQuery('#outputtext1').on('change', function() {
//I know that this logic can be put in onClick function above instead
var number = document.getElementById("outputtext1").value;
if( number <= 3){
document.getElementById("outputtext2").value = "low";
} else if (number < 10){
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10){
document.getElementById("outputtext2").value = "high";
}
});
Thank you in advance!
You can use jQuery('#outputtext1').trigger("change"); in the button element click event.
Example:
jQuery('#button1').on('click', function() {
document.getElementById("outputtext1").value = parseInt(document.getElementById("outputtext1").value) + 1;
jQuery('#outputtext1').trigger("change");
});
jQuery('#outputtext1').on('change', function() {
var number = document.getElementById("outputtext1").value;
if (number <= 3) {
document.getElementById("outputtext2").value = "low";
} else if (number < 10) {
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10) {
document.getElementById("outputtext2").value = "high";
}
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" readonly/>
<input type="text" id="outputtext2" value="" />
Try this:Change the value for outputtext1 and fire change event on it
jQuery('#button1').on('click', function() {
var value = jQuery("#outputtext1").val();
value = (parseInt(value) || 0) + 1;
jQuery("#outputtext1").val(value).change();
});
jQuery('#outputtext1').on('change', function() {
var number = (parseInt($(this).val()) || 0) + 1;
if( number <= 3){
jQuery("#outputtext2").val("low");
} else if (number < 10){
jQuery("#outputtext2").val("medium");
} else if (number >= 10){
jQuery("#outputtext2").val("high");
}
});
JSFiddle
NOTE: You can use jQuery id selector and '.va()` function instead of Javacript as shown in code above.
You could use $('#outputtext1').trigger("change") on button click
DEMO
$('#button1').on('click', function() {
$('#outputtext1').val(+$('#outputtext1').val()+1);
$('#outputtext1').trigger("change");
});
$('#outputtext1').on('change', function() {
var number = document.getElementById("outputtext1").value;
if (number <= 3) {
document.getElementById("outputtext2").value = "low";
} else if (number < 10) {
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10) {
document.getElementById("outputtext2").value = "high";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" readonly/>
<input type="text" id="outputtext2" value="" />
Either you can trigger the change event or create a generic function and call it on both click and change event. Its better to call generic function rather then triggering the event from event.
// find elements
var banner = $("#banner-message")
var button = $("button")
$('#button1').on('click', function() {
document.getElementById("outputtext1").value = parseInt(document.getElementById("outputtext1").value) + 1;
$('#outputtext1').trigger('change');
});
$('#outputtext1').on('change', function() {
var number = document.getElementById("outputtext1").value;
if (number <= 3) {
document.getElementById("outputtext2").value = "low";
} else if (number < 10) {
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10) {
document.getElementById("outputtext2").value = "high";
}
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" />
<input type="text" id="outputtext2" value="" />
<!-- this should be changed when the value of outputtext1 is changing -->
// find elements
var banner = $("#banner-message")
var button = $("button")
$('#button1').on('click', function() {
document.getElementById("outputtext1").value = parseInt(document.getElementById("outputtext1").value) + 1;
validateInput();
});
$('#outputtext1').on('change', function() {
validateInput();
});
function validateInput() {
var number = document.getElementById("outputtext1").value;
if (number <= 3) {
document.getElementById("outputtext2").value = "low";
} else if (number < 10) {
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10) {
document.getElementById("outputtext2").value = "high";
}
}
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" />
<input type="text" id="outputtext2" value="" />
<!-- this should be changed when the value of outputtext1 is changing -->
try this fiddle
I am getting the selector attribute value with $('#outputtext1').attr('value') so that it will not break and change the value at runtime[Please check the value in DOM]. At the same time I am triggering a change event on button click.
jQuery('#button1').on('click', function() {
var x = $('#outputtext1').attr('value');
x = parseInt(x) +1;
$('#outputtext1').attr("value", x);
jQuery('#outputtext1').trigger("change");
});
jQuery('#outputtext1').on('change', function() {
var number = $('#outputtext1').attr('value');
if( number <= 3){
document.getElementById("outputtext2").value = "low";
} else if (number < 10){
document.getElementById("outputtext2").value = "medium";
} else if (number >= 10){
document.getElementById("outputtext2").value = "high";
}
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">button</button>
<input type="text" id="outputtext1" value="1" />
<input type="text" id="outputtext2" value="" />

Javascript timer, with stop button

I have a big problem with my JavaScript timer. Everything working fine, except 1 button: STOP! I cant figure out how to stop everything on my counter (like reset every input and the counter). Any ideas how can I fix this?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Feladat 5</title>
</head>
<body>
<form>
<label>Indulás: </label><input type="number" id="n_start" placeholder="1000"/> <label> (4 számjegyű
szám)</label><br /><br />
<label>Megállás: </label><input type="number" id="n_end" placeholder="1008"/> <label> (4 számjegyű szám)</label><br/><br />
<label>Számolás léptei: </label><input type="number" id="n_count" placeholder="1"/> <br /><br />
<label>Időközönti számolás: </label><input type="number" id="n_timer" placeholder="1"/> <label> (másodpercben)</label><br /><br />
</form>
<label>Számláló: </label><span id="counter">0</span> <br /><br />
<button id="first" type="button" onclick="count()">Start</button>
<button id="pause" type="button" style="display:none;" onclick="show_resume()">Pause</button>
<button id="resume" type="button" style="display:none;" onclick="show_pause()">Resume</button>
<button id="stop" type="button" name="stop">Stop</button>
<script>
function counterLoop(callback, delay)
{
var id
,start
,remaining = delay;
this.pause = function()
{
window.clearTimeout(id);
remaining -= new Date() - start;
};
var resume = function()
{
start = new Date();
id = window.setTimeout(function()
{
remaining = delay;
resume();
callback();
}, remaining);
};
this.resume = resume;
this.resume();
}
function count()
{
var startValue = document.getElementById("n_start").value;
var endValue = document.getElementById("n_end").value;
var countValue = document.getElementById("n_count").value;
var timerValue = document.getElementById("n_timer").value;
var count = startValue;
if (startValue == "" || endValue == "" || countValue == "" || timerValue == "")
{
alert("Minden mező kitöltése kötelező!");
}
else
{
if (startValue < 999 || endValue < 999)
{
alert("Legalább 4 számjegyű kell legyen az érték!")
}
else
{
var math_check = endValue - startValue;
if (math_check % countValue != 0 )
{
alert("A számlálás léptei túl lépnék a megállást.");
}
else
{
var counter = new counterLoop(function ()
{
if (startValue <= endValue)
{
if (countValue == 1)
{
++count;
if (count == endValue )
{
counter.pause();
document.getElementById('pause').style.display = 'none';
document.getElementById('resume').style.display = 'none';
document.getElementById('first').style.display = 'inline';
counter = 0;
}
}
else
{
count = +countValue + +count;
if (count == endValue)
{
counter.pause();
document.getElementById('pause').style.display = 'none';
document.getElementById('resume').style.display = 'none';
document.getElementById('first').style.display = 'inline';
counter = 0;
}
}
}
document.getElementById('counter').innerHTML = count;
}, timerValue * 1000);
document.getElementById('pause').addEventListener('click', function () {
counter.pause()
}, false);
document.getElementById('resume').addEventListener('click', function () {
counter.resume()
}, false);
document.getElementById('pause').style.display = 'inline';
document.getElementById('first').style.display = 'none';
}
}
}
};
function show_resume()
{
document.getElementById('resume').style.display = 'inline';
document.getElementById('pause').style.display = 'none';
}
function show_pause()
{
document.getElementById('resume').style.display = 'none';
document.getElementById('pause').style.display = 'inline';
}
</script>
</body>
</html>
do you want to stop that timer and resume or just stop and reset all the fields?

How to put Stop and Reset button in html and javascript

I need help,
How to put Stop and Reset button in html and javascript
Here my countdown javascript and html code and also put chrome notifications with sound,
sounds loop notify me left 10 Seconds after countdown then 0 notify me in chrome notification, and also show countdown value in page title
function do_countdown() {
var start_num = document.getElementById("value").value;
var unit_var = document.getElementById("countdown_unit").value;
start_num = start_num * parseInt(unit_var);
var countdown_output = document.getElementById('countdown_div');
if (start_num > 0) {
countdown_output.innerHTML = format_as_time(start_num);
var t=setTimeout("update_clock(\"countdown_div\", "+start_num+")", 1000);
}
return false;
}
function update_clock(countdown_div, new_value) {
var countdown_output = document.getElementById(countdown_div);
var new_value = new_value - 1;
if (new_value > 0) {
new_formatted_value = format_as_time(new_value);
countdown_output.innerHTML = new_formatted_value;
var t=setTimeout("update_clock(\"countdown_div\", "+new_value+")", 1000);
} else {
countdown_output.innerHTML = "Time's UP!";
}
}
function format_as_time(seconds) {
var minutes = parseInt(seconds/60);
var seconds = seconds - (minutes*60);
if (minutes < 10) {
minutes = "0"+minutes;
}
if (seconds < 10) {
seconds = "0"+seconds;
}
var return_var = minutes+':'+seconds;
return return_var;
}
And also html
<form id="countdown_form" onSubmit="return do_countdown();">
Countdown from: <input type="text" style="width: 30px" id="value" value="10" text-align="center"/>
<select id="countdown_unit">
<option value="1">Seconds</option>
<option value="60">Minutes</option>
<option value="3600">Hours</option>
</select>
<input type="submit" value="Start" />
<!--<input type="button" value="Reset" id="reset">-->
</form>
<div id="countdown_div"> </div>
javascript
changes
1.taken window variables t1,t2 where the timers are going to be assigned
2.added a button(name:reset),which on click calls doReset function
3.added doStuff function
window.t1=null;
window.t2=null;
function do_countdown() {
var start_num = document.getElementById("value").value;
var unit_var = document.getElementById("countdown_unit").value;
start_num = start_num * parseInt(unit_var);
var countdown_output = document.getElementById('countdown_div');
if (start_num > 0) {
countdown_output.innerHTML = format_as_time(start_num);
window.t1=setTimeout("update_clock(\"countdown_div\", "+start_num+")", 1000);
}
return false;
}
function update_clock(countdown_div, new_value) {
var countdown_output = document.getElementById(countdown_div);
var new_value = new_value - 1;
if (new_value > 0) {
new_formatted_value = format_as_time(new_value);
countdown_output.innerHTML = new_formatted_value;
window.t2=setTimeout("update_clock(\"countdown_div\", "+new_value+")", 1000);
} else {
countdown_output.innerHTML = "Time's UP!";
}
}
function format_as_time(seconds) {
var minutes = parseInt(seconds/60);
var seconds = seconds - (minutes*60);
if (minutes < 10) {
minutes = "0"+minutes;
}
if (seconds < 10) {
seconds = "0"+seconds;
}
var return_var = minutes+':'+seconds;
return return_var;
}
function doReset(){
window.clearTimeout(window.t1);
window.clearTimeout(window.t2);
document.getElementById('countdown_div').innerHTML="";
}
HTML
<form id="countdown_form" onSubmit="return do_countdown();">
Countdown from: <input type="text" style="width: 30px" id="value" value="10" text-align="center"/>
<select id="countdown_unit">
<option value="1">Seconds</option>
<option value="60">Minutes</option>
<option value="3600">Hours</option>
</select>
<input type="submit" value="Start" />
<input type="button" onClick="return doReset();" value="Reset" id="reset">
</form>
<div id="countdown_div"> </div>
Use the reset attribute in your form to clear the form input values
<input type="reset"value="Reset">
Take a look here http://jsfiddle.net/05y89wn3/14/
you have to clear the timeout ,reset the form and change the html value of the countdown_div
var reset = document.getElementById("reset_button");
var t;
reset.onclick = function() {
clearTimeout(t);
document.getElementById("countdown_form").reset();
document.getElementById("countdown_div").innerHTML="";
}

lastChild.remove() doesn't work on IE

I want to dynamically add and remove input files, my code works great on all browsers without Internet Explorer. Can anyone help me to resolve my problem?
Here is the Javascript:
<script>
var counter = 1;
var min = 1;
var max = 20;
function addInput(divName) {
if (counter == max) {
alert("Max limit!");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = '<input type="file" name="file[]" id="file"><br>';
document.getElementById(divName).appendChild(newdiv);
document.getElementById("qty").value++;
counter++;
}
}
function remInput(divName) {
if (counter == min) {
alert("Min limit!");
}
else {
var element = document.getElementById(divName);
element.lastChild.remove();
document.getElementById("qty").value--;
counter--;
}
}
</script>
And here is the HTML code:
<input type="button" value="-" onClick="remInput('plus');">
<input type="text" name="qty" id='qty' size='2' style="text-align: center" disabled value="1">
<input type="button" value="+" onClick="addInput('plus');">
<div id="plus">
<input type="file" name="file[]" id="file"><br>
</div>
Thank you.
Its seems that remove() is not supported in IE, do add condition in your code, if particular function is supported in your browser(in this case remove() function)
Please refer below working add.
<script>
var counter = 1;
var min = 1;
var max = 20;
function addInput(divName) {
if (counter == max) {
alert("Max limit!");
}
else {
var newdiv = document.createElement('div');
var inputid="file"+counter;
newdiv.innerHTML = '<input type="file" name="file[]" id='+inputid+'><br>';
document.getElementById(divName).appendChild(newdiv);
document.getElementById("qty").value++;
counter++;
}
}
function remInput(divName) {
if (counter == min) {
alert("Min limit!");
}
else {
var element = document.getElementById(divName);
if(element.lastChild.remove!= undefined)
element.lastChild.remove();
else
element.lastChild.parentNode.removeChild(element.lastChild);
document.getElementById("qty").value--;
counter--;
}
}
</script>

Countdown timer is not running

OK thanks all. The problem is solved after i see comment.
My countdown timer is not running.
<script type="text/javascript">
function timer(){
var count = document.getElementById("numb").value;
var counter=setInterval(timer, 1000);
var detik = count;
do {
count--;
document.getElementById("timer").innerHTML=count + " secs";
if (count<=0) {
count = detik+1;
}
} while (count===detik+1);
}
</script>
<input type="text" id="numb" name="numb" value=""></input>
<input type="button" value="click" onClick="timer();"/>
<span id="timer"></span>
There were some logic problem with your timer function. Check this fiddle.
HTML
<input type="text" id="url" name="url" value=""></input>
<input type="button" value="click" onClick="timer();" />
<span id="timer"></span>
JavaScript
function timer() {
clearInterval(counter);
var count = parseInt(document.getElementById("url").value);
document.getElementById("timer").innerHTML = count + " secs";
var counter = setInterval(function () {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML = count + " secs";
}, 1000);
};
There is a logical error in your code. Say, you gave 5 as input and clicked the button.
The count stores 5 and so is detik.
Inside the do-while loop, the count is decremented,(now 4). Then this is being displayed to the screen. The if condition isn't satisfied. But the do-while condition is also not true. Hence it comes out of the loop.
This whole process repeats again since you have setInterval for the function. On the whole you see the counter remaining the same.
What you need to do is this:
HTML:
<input type="text" id="numb" name="numb" value=""></input>
<input type="button" value="click" onClick="start_timer();"/>
<span id="timer"></span>
JS:
var count;
var intrv;
function start_timer(){
count = document.getElementById("numb").value;
count = parseInt(count);//convert to int..
intrv = setInterval(timer, 1000);
}
function timer(){
document.getElementById("timer").innerHTML = count + " secs";
count--;
if(count<0)
{
clearInterval(intrv);
}
}
JAVASCRIPT
var count = 0;
var inter;
function timer1(flag){
if(flag == 1)
{
count = document.getElementById("url").value;
console.log(count);
flag = 0;
}
count--;
document.getElementById("timer").innerHTML= count + " secs";
if(count<=0){
clearTimeout(inter);
}else{
inter = setTimeout(function(){timer1(0)},1000);
}
}
HTML
<input type="text" id="url" name="url" value="">
<input type="button" value="click" onclick="timer1(1);"/>
<div id="timer"></div>
I changed it like this and it works:
window.timer = function timer() {
var count = document.getElementById("numb").value;
var cTimer = document.getElementById("timer").innerHTML;
if(cTimer && !isNaN(parseInt(cTimer))) cTimer = parseInt(cTimer) - 1;
else cTimer = count;
if(cTimer==0) return;
document.getElementById("timer").innerHTML = cTimer + " secs";
setTimeout(timer, 1000);
}
and this your working DEMO.

Categories