Javascript: Automatically clicking a button when countdown is complete - javascript

I am trying to display the alert message when the countdown is complete, I am trying the following code but its does not work please help!
<!DOCTYPE html>
<html>
<body>
<p id=count></p>
<form>
<button id="autoClickBtn" onclick="autoClick()">Click me</button>
</form>
<script>
function autoClick(){alert("I am loaded and automatically clicked");}
var count = 5;
var interval = setInterval(function () {
document.getElementById('count').innerHTML = count;
count--;
if (count === -1) {
clearInterval(interval);
window.onload = function () { document.getElementById("autoClickBtn").click() };
}
}, 1000 );
</script>
</body>
</html>

If you want to alert once after a certain time. Use setTimeout function. You can add the delay in milliseconds. In the example below I have added a delay of 2 secs.
setInterval, on the other hand, will run indefinitely again and again after time period defined
setTimeout(function () {
window.alert('This is an alert');
}, 2000);

Related

Refreshing page

Am having a problem with my script
i want to refresh the page every 30 seconds,
But ONLY when you are NOT typing into textbox
OTHER IMPORTANT THING
page should refresh if am typing into textbox and i stop without clicking send button for 1 minute (Idle)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
var isTyping = false;
$("#inputbox").focus(function() {
isTyping = true;
});
$("#inputbox").blur(function() {
isTyping = false;
});
// Refresh page, but ONLY when you are NOT typing
var refreshId = setInterval(function() {
if (!isTyping) {
window.setTimeout( function() {
window.location.reload();
)}, 30000);
}
)}
$.ajaxSetup({ cache: false });
</script>
</head>
<body>
<input type="text" id="inputbox">
<button type="button">Click Me!</button>
</body>
</html>
Rather than check for "isTyping", you can cancel the setTimeout and create a new one each time the user does something.
Cancel/start a new timer (60s) on focus/input.
Cancel/start a new timer (30s) on blur.
Start the timeout when the page loads.
Here's the implementation (timeout changed to x100 ms instead of x1000 just for testing and some output to see what's happening)
var timerId;
function restartTimer(s) {
clearInterval(timerId);
timerId = setTimeout(() => {
//window.location.reload()
$("#out").text("times up");
}, s * 100 /* * 1000, 100 for testing */);
$("#out").text("timer restarted: " + s + "s " + timerId);
}
$("input").on("focus input", () => restartTimer(60));
$("input").on("blur", () => restartTimer(30));
// "technically" startTimer, but it's the same
restartTimer(30);
// optionally only if "idle"
//$("document").on("mousemove click", () => restartTimer(30));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="text" id="inputbox">
<button type="button">Click Me!</button>
<div id="out"></div>

Timer will not fire "onclick". Fires on page load

I am trying to teach myself to code. I am coding a simple quiz. I would like my timer to fire on "start", and eventually, "next question". My timer starts once the page loads. Not sure why.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button id="b1">Click Me!</button>
<p id="demo"></p>
<script>
var sec = 5;
var time = setInterval(myTimer, 1000);
function myTimer() {
document.getElementById("b1").onclick = function() {
myTimer()
};
document.getElementById('demo').innerHTML = sec + "sec.";
sec--;
if (sec <= -1) {
clearInterval(time);
// alert("Time out!! :(");
document.getElementById("demo").innerHTML="Time's up!";
}
}
Have tried several different ways, including "addEventListener". Nothing seems to work.
If you take a look at a minimal example you'll see that this also runs as soon as the page is loaded. Here setInterval() is called when the script loads in the page. In turn the run() function is called every second.
var timerID = setInterval(run, 1000);
function run() {
console.log("I'm running");
}
Think of the difference between var timer = run; and var timer = run(). The first assigns the function run to timer. The later executes run() and assigns the return value.
Here's your code with comments:
var sec = 5;
// start interval timer and assign the return value "intervalID" to time
var time = setInterval(myTimer, 1000);
// to be called every second
function myTimer() {
// assign an onclick handler to "b1" EVERY SECOND!
document.getElementById("b1").onclick = function() {
myTimer()
};
// update the demo DOM element with sec
document.getElementById('demo').innerHTML = sec + "sec.";
sec--;
if (sec <= -1) {
clearInterval(time);
// alert("Time out!! :(");
document.getElementById("demo").innerHTML="Time's up!";
}
}
For a solution I've moved setInterval into the onclick handler and moved said handler assignment out of the myTimer function as you only want to setup your handlers once.
I've also renamed time to timerID to make it clear what it is.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button id="b1">Click Me!</button>
<p id="demo"></p>
<script>
var sec = 5;
var timerID;
document.getElementById("b1").onclick = function() {
timerID = setInterval(myTimer, 1000);
};
function myTimer() {
document.getElementById('demo').innerHTML = sec + "sec.";
sec--;
if (sec <= -1) {
clearInterval(timerID);
// alert("Time out!! :(");
document.getElementById("demo").innerHTML="Time's up!";
}
}
</script>
</body>
</html>
I would suggest a couple of extra exercises to help you:
Reset the timer so that you can click on the button to start the timer again
Prevent the timer being started again (which would run multiple timers with different IDs) while a timer is running
The myTimer() function is never invoked. Even if you invoke it, it does not take any action. It's just repeating itself on click.
So, instead of:
function myTimer() {
document.getElementById("b1").onclick = function() {
myTimer()
};
Try adding an Event Listener:
document.getElementById("b1").addEventListener('click', function() {
// inside here you put the code for going into next question
})
Or use just the same code, but not inside a function, and its content to be a meaningful code that leads to the next answer:
document.getElementById("b1").onclick = function() {
// code to proceed into next question
}

Countdown in JS

I'm trying to have, on a registered.php page, a countdown that shows a timer that starts from 3 secs and goes down second by second, redirecting to another page in the end.
However, when I load the page in my browser i'm redirected to the other page in an instant. Can someone help me figure out why?
The registration was successful, you will be redirected in <span id="num"></span> seconds.
<script>
$(document).ready(function (){
for (var i = 3; i>0; i--) {
setTimeout(function () {
$("#num").html(i);
},1000);
}
window.location.replace("login.html");
});
</script>
Since this is a redirection page, you might not want to include the whole jQuery library for this bit of code:
var remaining = 3;
function countdown() {
document.getElementById('num').innerHTML = remaining;
if (!remaining--) {
window.location.replace("login.html");
}
setTimeout(countdown, 1000);
}
window.onload = countdown;
JS Fiddle Demo
Proper way:
$(document).ready(function () {
var i = 3;
$("#num").html(i);
setInterval(function () {
if(i==0){window.location.replace("login.html");}
i--;
$("#num").html(i > -1 ? i : 0);
}, 1000);
});
setInterval would execute every second the function, but with the code you had, you just set setTimeout to execute after a second, but it didn't stop you from looping further. So you immediately had three timeouts set and then redirected.
$(document).ready(function () {
var timer = 3;
var clearTime = setInterval(function(){
$("#num").html(timer--);
if(timer == 0){
window.clearInterval(clearTime);
window.location.replace("login.html");
}
},1000);
});

Problems with running 2 JavaScript "onload" functions

I have two JavaScript "onload" functions that I am trying to run on a webpage: a visual timer and a auto refresh function. I have implemented both in my webpage but although the timer runs, the Auto Refresh function will not run unless I remove the visual timer function from the script.
Here is the code for the webpage:
<!DOCTYPE html>
<HTML>
<HEAD>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
<TITLE>test</TITLE>
</head>
<body onload="JavaScript:timedRefresh(15000); timedText();">
<script>
window.onload = timedText;
function timedText() {
var txt = document.getElementById('txt'),
counter = 15;
var timer = setInterval(function () {
if(counter === 0) return clearInterval(timer);
txt.value = counter + " seconds";
counter--;
}, 1000);
}
</script>
<input type="text" id="txt" />
</body></HTML>
Any help in solving this problem would be greatly appreciated.
try with a small change:call timedRefresh() inside window.onload's timetext() function not in body onload.
<!DOCTYPE html>
<HTML>
<HEAD>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
<TITLE>test</TITLE>
</head>
<body>
<script>
window.onload = timedText;
function timedText() {
var txt = document.getElementById('txt'),
counter = 15;
timedRefresh(15000);
var timer = setInterval(function () {
if(counter === 0) return clearInterval(timer);
txt.value = counter + " seconds";
counter--;
}, 1000);
}
</script>
<input type="text" id="txt" />
</body></HTML>
The problem is the second one overrides the first. That is what you should be using addEventListener to add events.
window.addEventListener('load', timedText, false);
window.addEventListener('load', function(){timedRefresh(15000);}, false);
and if you need to support older IEs you need to look at attachEvent
BUT looking at the code why are you running two setTimeouts when all you need to do is when it hits zero call the redirect.
You can add multiple onload events using the addEventListener method, like so:
window.addEventListener("load", timedText, false);
window.addEventListener("load", timedRefresh(15000), false);
function timedText() {
var txt = document.getElementById('txt'),
counter = 15;
var timer = setInterval(function() {
if (counter === 0) return clearInterval(timer);
txt.value = counter + " seconds";
counter--;
}, 1000);
}
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",
timeoutPeriod);
}
You can find out more information about addEventListener here.
Here's a working codepen.

How do I separate functionality with Javascript code to set Timeout?

I have the following code:
var comparePanel = $(__this.NOTICE_BODY);
clearTimeout(__this._timeout);
comparePanel.addClass(__this.VISIBLE);
__this._timeout = setTimeout(function () {
comparePanel.removeClass(__this.CL_VISIBLE);
}, 3000);
}
})
The following has been repeated a few times:
__this._timeout = setTimeout(function () {
comparePanel.removeClass(__this.CL_VISIBLE);
}, 3000);
I want to be able to do something like this:
__this._timeout = setTimeout(comparePanel, 3000);
How do I define and call that function?
PS. I am very very new to JavaScript so any explanation of what is going on is greatly appreciated.
You can pass an existing function to setTimeout like this:
// declare named function
function comparePanelTick() {
comparePanel.removeClass(__this.CL_VISIBLE);
}
Then use it like you show in the question:
__this._timeout = setTimeout(comparePanelTick, 3000);
Note: you already have a variable named comparePanel so use something else for the function name.
See this sample
<!DOCTYPE html>
<html>
<body>
<p>Click the first button alert "Hello" after waiting 3 seconds.</p>
<p>Click the second button to prevent the first function to execute. (You must click it before the 3 seconds are up.)</p>
<button onclick="myFunction()">Try it</button>
<button onclick="myStopFunction()">Stop the alert</button>
<script>
var myVar;
function myFunction() {
myVar = setTimeout(function(){alert("Hello")}, 3000);
}
function myStopFunction() {
clearTimeout(myVar);
}
</script>
</body>
</html>
In this example, you can call it any time you want. However if you don't wrap your setTimeout() in a function, it'll be fired the second it gets initialized.
this._timeout = setTimeout(function(){
comparePanel();
}, 3000);
DEMO
function theTimeOutClass()
{
this._timeout = function(){
setTimeout(function(){
comparePanel();
}, 3000);
};
}
function comparePanel()
{
alert('I\'m comparing panels! ');
}
var toc = new theTimeOutClass();
toc._timeout();

Categories