settimeout using a variable input - javascript

I want to create a setTimeout with the timeout amount being input by the user.
e.g. I want the user to be able to delay the playback of an audio sample by manually inputting the delay time into a box.
Is it possible to trigger setTimeout from variable input or am I going about this the wrong way?

Yes, you can do this by collecting the number and using it as the timeout variable.
<input type="number" id="timeout">
Then you can collect it with .value
var timeout = +document.querySelector("#timeout").value;
setTimeout(my_function(), timeout);
Remember this is the number of milliseconds, so to make it into seconds multiply timeout by 1000.
var timeout = +document.querySelector("#timeout").value;
// convert from milliseconds to seconds
setTimeout(my_function(), timeout * 1000);
Here is a complete example with seconds.
function timeout() {
var milliseconds = +document.querySelector("#timeout").value;
var seconds = milliseconds*1000;
setTimeout(() => {
alert("Timeout has ended");
}, seconds);
}
<input type="number" id="timeout" value="1">
<button onclick="timeout()">Submit</button>

const delay = parseInt(window.prompt("number in millisecond"));
setTimeout(() => {
window.alert("Its took me " + delay + " millisecond to show up");
}, delay);
I wish this is what are you looking for

By using an <input> element you can have the user set a value for a delay. Then when you want to call the setTimeout, use the value of that input as the delay.
const fire = document.getElementById('fire');
const delay = document.getElementById('delay');
fire.addEventListener('click', () => {
const duration = Number(delay.value);
setTimeout(() => {
alert(`hello after ${duration}ms`);
}, duration);
});
<label for="delay">Set the delay</label>
<input type="number" id="delay" value="500">
<button type="button" id="fire">Fire</button>

Here is the Demo Code.
HTML:
<form>
<input type="number" name="delayTime"/>
<button>Submit Time Delay</button>
</form>
Javascript:
const form = document.querySelector("form");
form.addEventListener("submit",(e)=>{
e.preventDefault();
setTimeout(()=>{
document.querySelector(".audio").play()
},parseInt(`${form["delayTime"]000`}));
});
NOTE: You will need to give time as seconds, I have simply added 3 zeros to make it seconds.

Related

How do you stop displaying a div element (id) after a certain amount of time?

I have been coding a website, but I want a message to disappear/not display after a few seconds. I tried different code snippets but I cannot seem to plug them in properly with my code. Is there any way I could make it stop displaying after a certain amount of time?
var done = "Done!";
document.getElementById("done").innerHTML = done;
var startTime = new Date().getTime();
var interval = setInterval(function() {
if (new Date().getTime() - startTime > 2000) {
clearInterval(interval);
return;
}
done.getElementById.remove("done");
}, 2000);
<h2 style="color:green;" id="greendisp">
<span id="done"></span>
</h2>
You should use setTimeout
const done = "Done!";
document.getElementById("done").innerHTML = done;
setTimeout(() => {
document.getElementById("done").remove()
}, 2000)
<h2 style="color:green;" id="greendisp"><span id="done"></span></h2>
Try this.
This will use a timeout instead of an interval.
// Element to remove
const targetId = 'done';
// Set HTML of element with id 'done' to 'Done!'
document.getElementById(targetId).innerHTML = "Done!";
// Set a Timeout which will call the function inside after 2000ms (2 seconds)
setTimeout(function () {
// Remove the target element with id 'done'
document.getElementById(targetId).remove();
}, 2000);
<h2 style="color:green;" id="greendisp"><span id="done"></span></h2>

Javascript or Jquery function with timer that resets each time it is called

I am looking for a way to call a function that should wait for 1000 miliseconds before executing. And when the function is called again before the 1000 miliseconds are reached, the timer should restart. So that the function runs 1000 miliseconds after the last time it was called.
So let's say I have a button:
<button type="button" id="btnclick">Click Me!</button>
And I want to display an alert after exactly 1000 miliseconds after the last time it was clicked. But when the button is clicked a second time, before the 1000 miliseconds have past, then the timer should restart.
If someone clicks the button 1 time, then the alert displays 1 second after the click.
If someone clicks the button, and then clicks again after 999 miliseconds, and then again after again 999 miliseconds, then I want to run the function 1 second after the last click (so 2,98 seconds after the first click).
Is this possible? And how?
My Best guess would be something like:
function delay(callback, ms) {
var timer = 0;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
callback.apply(context, args);
}, ms || 0);
};
}
$('#btnclick').click(function(e){
console.log('I want to see this everytime the button is clicked, without any delay');
delay(waitFunction(),1000);
});
function waitFunction(){
console.log('I want to see this 1 second after the LAST click');
}
(inspiration from: Wait for function till user stops typing )
Yes it is possible. you just have to check if an timeout is already counting down and, if it is, reset it. Here is a simple example.
// set timer-variable
var timer = null;
//on button-click
$('#btnclick').click (function (e) {
//clear timeout if already applied
if (timer) {
clearTimeout (timer);
timer = null;
}
//set new timeout
timer = setTimeout (function () {
//call wait-function and clear timeout
waitFunction ();
clearTimeout (timer);
timer = null;
}, 1000);
});
function waitFunction () {
console.log ('I want to see this 1 second after the LAST click');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="btnclick">Click Me!</button>
I used lastclick variable to store date user clicked.
I defined lastclickworked variable to avoid double setTimeout calls. In settimeout function, i checked if 1 second passed, run the code. if 1 second doesn't passed then call settimeout again with 1 seconds- passed time
var lastclick=null;
var lastclickworked=true;
function clickMe(){
lastclick=new Date();
if(lastclickworked)
runcallback(1000);
}
function runcallback(milliseconds){
lastclickworked=false;
setTimeout(function(){
var current = new Date();
var milliseconds = (current.getTime() - lastclick.getTime());
if(milliseconds<1000){
runcallback(1000-milliseconds);
}else{
lastclickworked=true;
console.log('you clicked 1 second ago');
}
},milliseconds);
}
<button onclick="clickMe();">Click Me!</button>

How setTimeout function is working in this case? [duplicate]

This question already has answers here:
Recursive setTimeout in javascript
(2 answers)
Closed 5 years ago.
<body>
<input type="text" value="10" id="txtBox" /><br/><br/>
<input type="button" value="Start Timer" onclick="startTimer('txtBox')" />
<input type="button" value="Stop Timer" onclick="stopTimer()" />
<script type="text/javascript">
var intervalId;
function startTimer(controlId)
{
var control = document.getElementById(controlId);
var seconds = control.value;
seconds = seconds - 1;
if (seconds == 0)
{
control.value = "Done";
return;
}
else
{
control.value = seconds;
}
intervalId = setTimeout(function () { startTimer('txtBox'); }, 1000);
}
function stopTimer()
{
clearTimeout(intervalId);
}
</script>
</body>
I am new to JavaScript. I was going through some tutorial, the above code snippet I came across, which works completely fine for starting a countdown timer from 10 to 0 in every 1000 millisecond interval. I am confused that how setTimeout() is calling the function repeatedly, when it is supposed to call the function only once after waiting 1000 millisecond.
function startTimer(){...} is a named function. One advantage of named function is that it call itself from inside its body. The code you shared is exploiting this concept & the code inside setTimeout is calling the same function startTimer
intervalId = setTimeout(function() {
startTimer('txtBox');
}, 1000);
The startTimer() function will be called by the setTimeout() function. Then when the startTimer() function is executing, it will call the setTimeout() function again. So it is a lot like a loop.
You can also use setInterval instead:
intervalId = setInterval(function(){
startTimer('txtbox');
}, 1000);
use it outside the startTimer function. It will call the startTimer function once every 1000 milliseconds repeatedly.

Change setInveral/Timeout speed dynamically with range input

I wonder if it's possible to change setInterval or setTimeout speed dynamically with html5 range input? If so how do I do that? I've tried to save value from input to a variable and then set the variable as an Interval/Timeout time but It didn't work and the Interval/Timeout worked full speed on change.
Can anyone give me some examples, please? :)
var elem = document.querySelector('input[type="range"]');
var rangeValue = function(){
var newValue = elem.value;
var b = newValue;
delay = b;
setInterval(function(){
console.log("Hi")
}, delay);
}
elem.addEventListener("input", rangeValue);
<input name="1" type="range" min="1000" max="7000" step="10" value="0">
The input event is going to fire multiple times for the range input as it is slid, so when you think you are only setting 1 interval/timeout you are setting multiple. This gives the impression that your timer is running at fullspeed (which I assume you mean as if it was set to 0 delay).
What you can do to counter act that is save the timer id that is returned from setTimeout/Interval. Then immediately clear it at the beginning of the callback to make sure any previous timers are no longer running.
var elem = document.querySelector('input[type="range"]');
var timerId = null;
var rangeValue = function(){
clearInterval(timerId);
var delay = elem.value;
timerId = setInterval(function(){
console.log("Hi")
}, delay);
}
elem.addEventListener("input", rangeValue);
<input name="1" type="range" min="1000" max="7000" step="10" value="0">
You need to add two different things. First you need to store the current interval so you can clear it when a new one is set. Also you should add a timeout when the slider is changed so that you're not setting the interval at every value along the path.
var elem = document.querySelector('input[type="range"]');
var slideInput;
var currentInterval;
var rangeValue = function(){
if (currentInterval) {
clearInterval(currentInterval);
}
var newValue = elem.value;
var b = newValue;
delay = b;
currentInterval = setInterval(function(){
console.log("Hi")
}, delay);
}
elem.addEventListener("input", function()
{
if (slideInput) {
clearTimeout(slideInput);
}
slideInput = setTimeout(rangeValue, 250);
});
<input name="1" type="range" min="1000" max="7000" step="10" value="0">

Javascript variable update on input

I have a function where I'm trying to update one parameter based on the value of a range input
a.start = function () {
var t = 50;
var rangeInput = document.getElementById('speed');
rangeInput.addEventListener("change", function () {
t = document.rangeInput.value;});
setInterval(function () {
a.update();
a.draw();
}, t );
};
And honestly I'm getting frustrated, because I can't get this function to work dynamically. It somehow works simply with
a.start = function () {
var t = document.getElementById('speed');
setInterval(function () {
a.update();
a.draw();
}, t );
};
but only after I refresh the page. Honestly, my understanding of javascript is rather poor, I know it can be done using AJAX, but do I have to do it for such a simple thing? Any tips appreciated. HEre's html:
<form>
<label for="speed">
<input id="speed" type="range" name="points" min="10" max="2000" >Animation speed</label>
</form>
You need to cancel any running timer before you start a new one with a new time associated with it. Also, your code needs to be separated a bit.
// Place all this code at the bottom of the code, just before the </body>
var rangeInput = document.getElementById('speed');
var t = 500; // Default
var timer = null; // Reference to the interval timer
rangeInput.addEventListener("change", function(){
t = rangeInput.value;
// Cancel any previous timers
clearInterval(timer);
// Do the animation every t milliseconds
timer = setInterval(function(){
// Commented out only because we don't know what "a" is:
//a.update();
//a.draw();
// For debugging:
console.log(t);
}, t);
});
<form>
<label for="speed">
<input id="speed" type="range" name="points" min="10" max="5000" >Animation speed</label>
</form>
You could also do this using setTimeout() instead of setInterval():
// Place all this code at the bottom of the code, just before the </body>
var rangeInput = document.getElementById('speed');
var t = 500; // Default
var timer = null; // Reference to the interval timer
rangeInput.addEventListener("change", animate);
function animate(){
clearTimeout(timer);
t = rangeInput.value;
// Commented out only because we don't know what "a" is:
//a.update();
//a.draw();
// For debugging:
console.log(t);
// Do the animation every t milliseconds. Call the function recursively
timer = setTimeout(animate, t);
}
<form>
<label for="speed">
<input id="speed" type="range" name="points" min="10" max="5000" >Animation speed</label>
</form>

Categories

Resources