Changing interval time with a click of a button Javascript - javascript

I am trying to modify this code so it changes the interval time with a click of a button but I'm failing miserably. Pretty sure that the solution is very simple. Appreciate any help. Thanks!
// define quotes array
var quotes = [
"AAAA",
"BBBB",
"CCCC"
];
// initialise current quote index
var quoteIndex = 0;
// get interval time
var interval = document.getElementById("interval").value;
// set target element
var $target = $('.container').find('h1');
// create timer function
var quoteTimer = function() {
// set target text to current quote
$target.fadeIn().text(quotes[quoteIndex]);
// increment the current index, or reset to 0 if on the last quote
quoteIndex = quoteIndex < quotes.length - 1 ? quoteIndex + 1 : 0;
}
// fire it up..!
$(document).ready(function() {
setInterval(quoteTimer, interval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="interval" id="interval" value="" placeholder="Time" />
<input type="submit" name="button" id="button" value="Run" />
<div class="container">
<h1></h1>
</div>

We are adding this piece of code to yours :
// Handle the button click to stop the current setInterval and to launch a new one
$('#button').click(() => {
clearInterval(intervalDescriptor);
intervalDescriptor = setInterval(quoteTimer, parseInt($('#interval').val(), 10));
});
// define quotes array
const quotes = [
"AAAA",
"BBBB",
"CCCC"
];
// initialise current quote index
let quoteIndex = 0;
// get interval time
const interval = document.getElementById("interval").value;
// set target element
const $target = $('.container').find('h1');
// create timer function
quoteTimer = function() {
// set target text to current quote
$target.fadeIn().text(quotes[quoteIndex]);
// increment the current index, or reset to 0 if on the last quote
quoteIndex = quoteIndex < quotes.length - 1 ? quoteIndex + 1 : 0;
}
let intervalDescriptor = false;
// Handle the button click to stop the current setInterval and to launch a new one
$('#button').click(() => {
clearInterval(intervalDescriptor);
intervalDescriptor = setInterval(quoteTimer, parseInt($('#interval').val(), 10));
});
// fire it up..!
$(document).ready(function() {
intervalDescriptor = setInterval(quoteTimer, interval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="interval" value="" placeholder="Time" />
<input type="button" id="button" value="Run" />
<div class="container">
<h1></h1>
</div>

updated your jsfiddle
Just stop older timer and start new timer with new interval
Changes
$("#button").on("click", function() {
let v = parseInt($("#interval").val());
clearTimeout(intervalval);
intervalval = setInterval(quoteTimer, v);
})

You can clear it using clearInterval and set it again with the interval.
var intervalId;
$(function(){
intervalId = setInterval(quoteTimer, interval);
});
$("button").click(function(){
if (intervalId) clearInterval(intervalId);
intervalId = setInterval(quoteTimer, interval);
});

var quotes = [
"AAAA",
"BBBB",
"CCCC"
];
// initialise current quote index
var quoteIndex = 0;
// get interval time
var interval = document.getElementById("interval").value;
$('#button').click(function(){
var intervl=$('#interval').val();
intervl=intervl+"000";
setInterval(quoteTimer, intervl);
})
// set target element
var $target = $('.container').find('h1');
// create timer function
var quoteTimer = function() {
// set target text to current quote
$target.fadeIn().text(quotes[quoteIndex]);
// increment the current index, or reset to 0 if on the last quote
quoteIndex = quoteIndex < quotes.length - 1 ? quoteIndex + 1 : 0;
}
// fire it up..!
$(document).ready(function() {
//setInterval(quoteTimer, interval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="interval" id="interval" value="" placeholder="Time in seconds" />
<input type="submit" name="button" id="button" value="Run" />
<div class="container">
<h1></h1>
</div>

Add a button click event and set the value to the setInterval function.
var quotes = [
"AAAA",
"BBBB",
"CCCC"
];
$('#button').click(function(){
var quoteIndex = 0;
var interval = document.getElementById("interval").value;
console.log(interval);
var $target = $('.container').find('h1');
setInterval(function(){
$target.fadeIn().text(quotes[quoteIndex]);
// increment the current index, or reset to 0 if on the last quote
quoteIndex = quoteIndex < quotes.length - 1 ? quoteIndex + 1 : 0;
}, interval*1000);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="text" name="interval" id="interval" value="" placeholder="Time" />
<input type="submit" name="button" id="button" value="Run" />
<div class="container">
<h1></h1>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</div>
</body>
</html>

#Esko means to attach click event to button so on click of button event will fire with text value.
check below code.
var intervalID;
// fire it up..!
$(document).ready(function() {
$('#button').click(function(){
var interval = document.getElementById("interval").value;
clearTimeout(intervalID);
intervalID = setInterval(quoteTimer, interval);
});
});

It should be this instead:
// fire it up..!
$("#button").click(function() {
// define quotes array
var quotes = [
"AAAA",
"BBBB",
"CCCC"
];
// initialise current quote index
var quoteIndex = 0;
// get interval time
var interval = document.getElementById("interval").value;
// set target element
var $target = $('.container').find('h1');
// create timer function
var quoteTimer = function() {
// set target text to current quote
$target.fadeIn().text(quotes[quoteIndex]);
// increment the current index, or reset to 0 if on the last quote
quoteIndex = quoteIndex < quotes.length - 1 ? quoteIndex + 1 : 0;
}
setInterval(quoteTimer, interval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="text" name="interval" id="interval" value="" placeholder="Time" />
<input type="submit" name="button" id="button" value="Run" />
<div class="container">
<h1></h1>
</div>
Remember that you also want to cancel the previous timer and start another one on click. I didnĀ“t add that part to the code.

Related

JavaScript-limited click count

I've got a problem with limited click counter using JavaScript. I have tried suggestions below but it seems like my problem might be somewhere else.
HTML/Javascript Button Click Counter
Basically I want to count clicks x times, which is provided from <input type="number"> field. It looks like the script is not recognizing this item in counting function.
Below I'd like to share example code:
function myFunction() {
var count = 0;
var number = document.getElementById("amount").value;
var btn = document.getElementById("clickme");
var disp = document.getElementById("clicked");
btn.onclick = function() {
count++;
disp.innerHTML = count;
}
if (count > number) {
btn.disabled = true;
}
}
<!DOCTYPE html>
<html>
<body>
<input type="number" id="amount">
<p>how many times button should be clicked</p>
<p>Click the button.</p>
<div id="clicked"></div>
<button id="clickme" onclick="myFunction()">Click me</button>
<script>
</script>
</body>
</html>
Just remove the surrounding function and the onclick attribute.
Also, move the value retrieval and the disabled logic inside the listener, and convert the value to a number:
let count = 0;
const btn = document.getElementById("clickme");
const disp = document.getElementById("clicked");
const amount = document.getElementById("amount");
btn.onclick = function () {
count++;
disp.innerHTML = count;
const number = +amount.value;
if (count > number) {
btn.disabled = true;
}
}
<input type="number" id="amount" >
<p>how many times button should be clicked</p>
<p>Click the button.</p>
<div id="clicked"></div>
<button id="clickme">Click me</button>
You can simply your solution using the snippet below.
let count = 0;
const inp = document.getElementById("amount");
const countEl = document.getElementById("clicked");
function myFunction(e) {
if (++count >= Number(inp.value)) e.target.disabled = true;
}
<input type="number" id="amount">
<p>How many times button should be clicked</p>
<p>Click the button.</p>
<button id="clickme" onclick="myFunction(event)">Click me</button>
I would recommend something like this. The limit can be increased or decreased at any time to allow for more or less clicks. Once it reaches 0, the button will stop adding to the count -
const f =
document.forms.myapp
function update (event) {
const limit = Number(f.limit.value)
if (limit <= 0) return
f.limit.value = limit - 1
f.count.value = Number(f.count.value) + 1
}
f.mybutton.addEventListener("click", update)
<form id="myapp">
<input type="number" name="limit" value="10">
<button type="button" name="mybutton">click me</button>
<output name="count">0</output>
</form>
I have managed to count the click events with the limit provided by <input type="number"> field and adding data to the array. Additioanlly, I am trying to decrease dynamically the amount of click events and remove last records from array using another button. Basically I have NAN value when I try to get counter value to decrease it.
It looks like this:
HTML code:
<!DOCTYPE html>
<html>
<body>
<input type="number" id="amount">
<p>how many times button should be clicked</p>
<p> Add question</p> <input type="text" id="question">
<p>Click the button.</p>
<div id="clicked"></div>
<button id="clickme" >add me</button>
<button id="delme">
delete me
</button>
</body>
</html>
JS code:
var count = 0;
var i=0;
const btn = document.getElementById("clickme");
const disp = document.getElementById("clicked");
var amount = document.getElementById("amount");
var question = document.getElementById("question");
var tab;
btn.onclick = function () {
count++;
disp.innerHTML = count;
var number = +amount.value;
tab=new Array(number);
tab[i]=question.value;
console.log(tab[i] + i);
question.value=" ";
i++;
if (count == number) {
btn.disabled = true;
}
}
var delbtn=document.getElementById("delme");
var countdown = parseInt(document.getElementById("clicked"));
delbtn.onclick = function () {
console.log(countdown);
countdown--;
disp.innerHTML = countdown;
if (countdown == 0) {
btn.disabled = true;
}
}

How do I add a certain number each time when click?

I have var i = 14, and button that increment i++.
When I click on the button I have added every time +1.
Example 14, 15, 16, 17.
I want to do step not in with 1 but with 14. Example 14, 28, 42?
https://jsfiddle.net/xLwDgZODc/zkont5d4/
var i = 14;
$('.click').click(function() {
$('.result').text(i++);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class='result'></span>
<button class="click">Click</button>
You could add the wanted value to the variable.
var i = 14;
$('.click').click(function() {
$('.result').text(i += 14);
});
Just to add an alternative option, you could use <input type="number" /> as it offers exactly the functionality you want using the step attribute:
<input type="number" value="14" step="14" />
Then, if you want a variable that is updated with every increase/decrease, just add an eventListener:
var i;
stepper.addEventListener('input', () => { i = result.textContent = stepper.value; console.log(i); })
<input type="number" value="14" step="14" id="stepper" />
<span id="result">14</span>
Simple add your step to i , see below fiddle :
var i = 14;
var step = 14;
$('.click').click(function() {
$('.result').text(i);
i += step;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="click">click</button><br />
Result :<div class="result">
</div>
var i = 14;
$('.click').click(function() {
$('.result').text(i += 14);
});
//Since your increment is by 14 i+=14
I think that you want to increase the i variable by +1 each time until it's higher or equal to 14 then it starts to increase by +14.
Here is a script that i've made for your problem, hope you enjoy it!
var i = 0;
$('.click').click(function() {
i < 14 ? i++ : i += 14;
$("#counter").text(i);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="counter">0</span>
<button class="click">Click</button>

how to calculate the time keydown to keyup

this is the code, but it's not work,where is wrong.
<input type="text" name ="name" place="">
<button disabled="disabled">click</button>
<script>
$(function(){
var i = 0;
$('input').keydown(function(event) {
i++;
var temp = i;
setTimeout(function(){
var rate = (i-temp);
console.log(rate);
if(rate--){
$('button').attr('disabled',true);
}else{
$('button').attr('disabled',false);
}
},1000)
});
});
thx so much for you guys help
You can use JavaScript storage which is similar to session variables:
<script>
window.onload = function () {
document.onkeydown=(function (event) {
if (localStorage["Count"] == null) {
localStorage["Count"] = 0;
}
else {
localStorage["Count"]++;
}
alert("The count is: " + localStorage["Count"]);
});
}
</script>
in jquery you can use the following code :
KeyDown :
$("input").keydown(function(){ // when user push the key
// do something !!
});
KeyUp :
$("input").keyup(function(){ // when user is not pushing key enymore
// do something !!
});
Calculate time between keydown and keyup:
timebetween = 0;
var count = null;
$("input").keydown(function(){
timebetween = 0;
count = setInterval(function(){
timebetween++;
}, 1);
});
$("input").keyup(function(){
clearInterval(count);
$("body").append("<br>Time between keydown and keyup is "+timebetween+"ms");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
You can try this it will give you time in miliseconds.
$(document).ready(function(){
var startTime = false, endTime;
$(window).keypress(function(){
if(!startTime){
startTime = $.now();
}
});
$(window).keyup(function(){
endTime = $.now();
var keyPressedTime = (endTime - startTime);
console.info('keyyyUpppp', keyPressedTime)
startTime = false;
});
});
you can use this :
<!DOCTYPE HTML>
<html>
<head>
<title>Js Project</title>
</head>
<body>
<input type="text" id="txt" />
<div id="label"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var time = 0; // pressing time
var pressed = 0; // key is pushed or not ?
var timer = setInterval(calculate, 10); // calculate time
$("#txt").keydown(function(){
pressed = 1;
});
$("#txt").keyup(function(){
pressed = 0;
$("#label").html("Pressing Time : "+time+" ms");
time = 0
});
function calculate() { // increase pressing time if key is pressed !!
if (pressed == 1) {
time += 1;
}
}
</script>
</body>
</html>

I can't get setInterval to work for me

I have a function called start that is triggered when you push the start button. The start function calls another function called getRandomImage. I want getRandomImage to repeat every 5 seconds, but I just can't get the setInterval method to work for me. I've tried putting the interval on the start function, but that just causes it to fire off once, and doesn't repeat. I've tried putting the interval on the getRandomImages function, but then it doesn't do anything. Essentially I am trying to make a color blindness test that flashes a random image every 5 seconds until 30 images have passed or the user clicks a button. I've been banging my head against this for over 8 hours, and am really questioning my choice in programming languages right now, lol.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"
<title></title>
<link rel="stylesheet" href="ColorPerceptionTest.css">
</head>
<body>
<section>
<img src="Default.png" id="defaultimage">
<form>
<input type="button" id="Button1" value="" onClick="">
<input type="button" id="Button2" value="" onClick="">
<input type="button" id="Button3" value="" onClick="">
<br>
<input type="button" id="Start" value="Start" onClick="start()">
<input type="button" id="Help" value="Help" onClick="help()">
<br>
<p id="help"> </p>
</form>
</section>
<script>
var $ = function(id) {
return document.getElementById(id);
}
$("Button1").style.display = "none";
$("Button2").style.display = "none";
$("Button3").style.display = "none";
var imagesArray = ["3.gif", "05.gif", "5.gif", "6.gif", "7.gif",
"8.gif", "12.gif", "15.gif", "16.gif", "26.gif",
"29.gif", "42.gif", "45.gif", "73.gif",
"74.gif"];
var runTimer = setInterval(start, 5000);
function getRandomImage(imgAr, path) {
path = path || 'images/';
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
$("defaultimage").src = path + img;
$("Button1").style.display = "initial";
$("Button2").style.display = "initial";
$("Button3").style.display = "initial";
if(parseInt(img) < 8){
$("Button1").value = parseInt(img);
$("Button2").value = parseInt(img) - 2;
$("Button3").value = parseInt(img) + 1;
}else if(parseInt(img) > 7 && parseInt(img) < 29){
$("Button1").value = parseInt(img) - 2;
$("Button2").value = parseInt(img);
$("Button3").value = parseInt(img) + 1;
}else{
$("Button1").value = parseInt(img) - 5;
$("Button2").value = parseInt(img) - 9;
$("Button3").value = parseInt(img);
}
}
var start = function(){
$("help").innerHTML = "";
getRandomImage(imagesArray);
$("Start").style.display = "none";
$("Help").style.display = "none";
}
var help = function (){
$("help").innerHTML = "This is a test designed to help you determine" +
" if you have a problem with seeing colors. When you press start, a series of " +
"random images will be displayed. You have 5 seconds to read the number and " +
"select the correct button.";
}
</script>
</body>
Try moving the setInterval call to a point where start is defined...
Your code works fine in this fiddle.
var start = function(){
$("help").innerHTML = "";
getRandomImage(imagesArray);
$("Start").style.display = "none";
$("Help").style.display = "none";
}
var runTimer = setInterval(start, 5000);
Update: To make it more clear, had OP written function start() the posted code would have been properly hoisted. But, as he used a function expression, start is undefined when setInterval is called.
Another update: Here's a forked fiddle to correct the timer based on the button and the comments below.

Can't figure out Javascript Countdown

I need help making a Countdown timer!
The user types a value into a text field, the timer starts when a button is clicked.
The timer text decreases by one every second until it reaches zero.
I have code for the first step, but can't seem to get the second step to work. I know it needs to include a setTimeout and loop.
Heres the code so far :
HTML-
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div id="form">
<h2> COUNTDOWN</h2>
Seconds: <input type="text" name="seconds" id="seconds" /> <input type="button" value="Start!" id="start" /> <input type="button" value="Pause" id="pause" />
</div>
<div id="info">
</div>
<div id="countdown">
</div>
<script src="script.js"></script>
</body>
</html>
JAVASCRIPT-
window.onload = function(){
var startButton = document.getElementById("start");
var form = document.getElementById("seconds");
var pause = document.getElementById("pause");
var secDiv = document.getElementById("countdown");
var editSec = document.createElement("h1");
startButton.onclick = function (){
editSec.innerHTML = form.value;
secDiv.appendChild(editSec);
};
};
Here it goes:
var globalTime = form.value; //receive the timer from the form
var secDiv = document.getElementById("countdown");
function decreaseValue() {
globalTime = globalTime - 1;
secDiv.innerHTML = globalTime;
}
startButton.onclick = function (){
setTimeout(decreasValue(),1000);
};
//clear out the timers once completed
You need to use setInterval, not setTimeout. Add this code to the onclick function:
editSec.id = "editSec";
window.cdint = setInterval(function(){
var origVal = parseInt(document.getElementById("editSec").innerHTML);
document.getElementById("editSec").innerHTML = origVal - 1;
if(origVal - 1 <= 0){
window.cdint = clearInterval(window.cdint);
}
}, 1000);
Use setInterval
var time = 100;
var countdown = function(){
secdiv.innerHTML = time;
time--;
}
setInterval(countdown,1000);
You can use setTimeout if you want :
startButton.onclick = function () {
var value = parseInt(form.value);
editSec.innerHTML = value;
secDiv.appendChild(editSec);
setTimeout(function () {
editSec.innerHTML = --value < 10
? '<span style="color:red">' + value + '</span>'
: value;
if (value) {
setTimeout(arguments.callee, 1000);
}
}, 1000);
};

Categories

Resources