Edit settimeout on autofill javascript - javascript

I want to place a command that allows me to change the waiting time after the click, for example
var myVar;
function myFunction() {
myVar = setTimeout(alertFunc, 3000);
}
function alertFunc() {
alert("Hello!");
}
<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<button onclick="myFunction()">Try it</button>

This can easily be achieved with jQuery.
$(".my-button").on("click", function(e){
e.preventDefault();
setTimeout(function(){
alert("hello");
}, 3000);
})

Plunkr Example with enhanced code
JS
// Code goes here
var myVar;
function myFunction() {
// this is to make sure we don't spin up infinite timeouts and have zombie threads
if(myVar === undefined) {
myVar = setTimeout(alertFunc, 3000);
} else {
alert("already running...");
}
}
function alertFunc() {
alert("hello!");
// clears the thread
clearTimeout(myVar);
myVar = undefined;
}
Your Code
Your code seems to be working just fine, alert will work when not in the stack overflow sandbox and the only thing I added was clearing the timeout with clearTimeout this is so it doesn't continually run infinitely.
var myVar;
function myFunction() {
myVar = setTimeout(alertFunc, 3000);
}
function alertFunc() {
console.log("Hello!");
clearTimeout(myVar);
}
<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<button onclick="myFunction()">Try it</button>

Related

Run the function until the mouse button is pressed in JavaScript

I want the function to run continuously as long as the user presses the mouse button
But it runs only once and is printed once on the console
I do not know how to solve this problem
please guide me
function handleBye() {
return console.log("BYE");
}
function handleHello() {
return console.log("HELLO");
}
<button onmousedown="handleHello()">hello</button>
<button onmousedown="handleBye()">bye</button>
Maybe you are looking for setInterval and clearInterval:
let timer;
function stop() {
clearInterval(timer);
}
function handleHello() {
repeat(() => console.log("HELLO"));
}
function handleBye() {
repeat(() => console.log("BYE"));
}
function repeat(what) {
timer = setInterval(what, 200); // Schedule
what(); // Also do it immediately
}
<button onmousedown="handleHello()" onmouseup="stop()">hello</button>
<button onmousedown="handleBye()" onmouseup="stop()">bye</button>

Javascript/jQuery setInterval shown old value onclick re-call function

I'm working with setInterval function to replace text.
function loadData(set){
if(set == undefined){
var a = "Hello";
}
else{
var a = set;
}
setMe(a);
function setMe(val){
setInterval(function(){
$(".setMe").html(val);
}, 1000);
}
}
loadData();
$('#clickMe').on('click', function(){
loadData("Good");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="setMe"></div>
<button id="clickMe">Click Me</button>
When I try to click the button, it will change the text to be Good. But why the old text is still shown alternate with Hello? You can try on the demo.
What I want is replace the text only to be Good.
You're calling loadData which starts the first interval setting the text to "Hello". Then when you're clicking the button, it starts another interval which sets the text to "Good". The problem is that you now have 2 intervals both setting the text value. The intervals will both keep running forever.
What you need is to use setInterval instead, which will only delay the change of the text value, instead of repeatedly changing it.
function loadData(set){
if(set == undefined){
var a = "Hello";
}
else{
var a = set;
}
setMe(a);
function setMe(val){
setTimeout(function(){
$(".setMe").html(val);
}, 1000);
}
}
loadData();
$('#clickMe').on('click', function(){
loadData("Good");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="setMe"></div>
<button id="clickMe">Click Me</button>
setInterval is for running function repeatedly at regular interval, unless cleared.
What is happening :
You are calling your function twice and hence two intervals are running. One setting the value to Hello and other setting the value to Good.
You can replace this with setTimeout, which runs a function once, after a delay.
function loadData(set){
if(set == undefined){
var a = "Hello";
}
else{
var a = set;
}
setMe(a);
function setMe(val){
setTimeout(function(){
$(".setMe").html(val);
}, 1000);
}
}
loadData();
$('#clickMe').on('click', function(){
loadData("Good");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="setMe"></div>
<button id="clickMe">Click Me</button>
You need to change where variable a is declared
And also setInterval is unnecessary here as you want to fire your action only once (and setInterval is repeated).
function loadData(set){
var a;
if(set == undefined){
a = "Hello";
}
else{
a = set;
}
function setMe(val){
setTimeout(function(){
$(".setMe").html(val);
}, 1000);
}
setMe(a);
}
loadData();
$('#clickMe').on('click', function(){
loadData("Good");
});

How to stop an onended function onclick

I have an onclick shuffle function that executes everytime the audio finishes. It works all fine, but I want to make another button that stops its execution.
Please please help with an example
Full Code:
<button onclick="test();stats();auto()">Shuffle</button>
<button id="abort" onclick='exitauto()'>Stop Shuffle</button>
<script>
function exitauto(){
}
</script>
<script>
function stats() {
if(document.getElementById("audio").src == "test.mp3")
{
document.getElementById("p2").innerHTML = "some song";
document.getElementById("playerimg").src="img.png";
};
}
</script>
<script>
function auto(){
var aud = document.getElementById("audio");
aud.onended = function shuf() {
test();
stats();
};
}
</script>
<script>
function test() {
var values = ['test.mp3',
],
valueToUse = values[Math.floor(Math.random() * values.length)];
document.getElementById("audio").pause();
document.getElementById("audio").setAttribute('src', valueToUse);
document.getElementById("audio").load();
document.getElementById("audio").play();
};
</script>
You can add a global variable which can be used to decide whether to call the test() and stats() function in the auto function or not. You can set that variable to true when clicked on start and false when clicked on stop

block function execution during setTimeout

I have a function that I call when I press a button. My goal is to print "hello" in the console after 5 seconds and, if I press the button during the 5 seconds of waiting, nothing at all.
The problem is that, if I press the button while i'm waiting the 5 seconds, in the console I still get more than one "hello". What am I doing wrong?
Here is the Javascript code:
function foo(){
var block = false;
if(!block){
block = true;
myVar = setTimeout(checkAgain, 5000);
}
function checkAgain(){
console.log("hello");
block = false;
}
}
And the HTML:
<button id="button" onClick="foo();">Click me!</button>
You don't need to manually handle the "block", you can just cancel the call with clearTimeout. This seems to be more natural for me - when you click once you say "call this function in 5 seconds", and when you click it again you say "don't call it".
var timeout = null;
var button = document.querySelector("#btn");
button.onclick = function()
{
if (timeout)
{
clearTimeout(timeout);
timeout = null;
}
else
{
timeout = setTimeout(function() {
timeout = null;
run();
}, 1000); // should be 5000, just for test
}
};
function run()
{
console.log("Hello world");
}
<input type="button" id="btn" value="Click me">
You're not doing anything to block subsequent calls. block is a local variable inside foo, so there's a different one for each call to foo.
Instead, you have to have block outside foo:
var myVar;
var block = false;
function foo(){
if(!block){
block = true;
myVar = setTimeout(checkAgain, 5000);
}
function checkAgain(){
console.log("hello");
block = false;
}
}
document.getElementById("btn").addEventListener("click", foo);
<input type="button" id="btn" value="Click me">
That also means that checkAgain doesn't have to be recreated for every call to foo, since it doesn't need anything local to foo anymore:
var myVar;
var block = false;
function foo(){
if(!block){
block = true;
myVar = setTimeout(checkAgain, 5000);
}
}
function checkAgain(){
console.log("hello");
block = false;
}
document.getElementById("btn").addEventListener("click", foo);
<input type="button" id="btn" value="Click me">
(I assume all of this is in a scoping function or module so these aren't globals.)
That said, the button will remain active, giving the user the impression he/she could click it. Instead, you might consider making it possible for foo to disable and re-enable the button.
that is because you have defined variable 'block' in the scope of the function 'foo' and it is been initiated again every time you call the function. the correct implementation is:
var block = false;
function foo(){
if (!block) {
block = true;
myVar = setTimeout(checkAgain, 5000);
}
function checkAgain() {
console.log("hello");
block = false;
}
}

How to perform an action every couple of seconds?

Can someone quickly and simply explain to me how to perform an action every couple of seconds using
var timeOut = setTimeout(FunctionName, 5000);
I want to run a function every 5 seconds.
As you asked for a method using setTimeout:
function doStuff() {
console.log("hello!");
setTimeout(doStuff, 5000);
}
setTimeout(doStuff, 5000);
But it would probably be better to use setInterval:
function doStuff() {
console.log("hello!");
}
setInterval(doStuff, 5000);
Just put setTimeout at the end inside your function, with a call to itself - like a delayed tail-recursion.
Use setInterval:
var timeOut = setInterval(nextNotice, 5000);
var myFunction = function() {
//Do stuff
AnotherFunction();
};
var timeOut = setInterval(myFunction, 2000);
you can do something like:
$(document).ready(function ()
{
setTimeout(nextNotice, 5000);
}
function nextNotice()
{
// do stuff
setTimeout(nextNotice, 5000);
}
In the example below, when a button is clicked, the input field will start to count (for ever), starting at 0.
<html>
<head>
<script type="text/javascript">
var c = 0;
var t;
var timer_is_on = false;
function timedCount() {
document.getElementById('txt').value = c;
c = c + 1;
t = setTimeout(timedCount, 1000);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on = true;
timedCount();
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()">
<input type="text" id="txt" />
</form>
</body>
</html>

Categories

Resources