How to create automatic Refresh when Checkbox is clicked? - javascript

I want to create automatic refresh when check box click. countdown timer running well but still no luck when I click the checkbox
this is my code. need help to review my code
// COUNTDOWN METHOD.
window.setInterval(function() {
counter--;
if (counter >= 0) {
var span;
span = document.getElementById("cnt");
span.innerHTML = counter;
}
if (counter === 0) {
clearInterval(counter);
}
}, 1000);
window.setInterval('refresh()', 10000);
// REFRESH OR RELOAD PAGE.
function refresh() {
window.location.reload();
}
<input type="checkbox"> This page will reload in <span id="cnt" style="color:red;">30</span> Seconds

Add an onclick handler:
<input type="checkbox" onclick="refresh()">

In the html, call a function which should be getting executed on checkbox selection
<input type="checkbox" id="myCheck" onclick="checkboxClicked()"> This page will reload in <span id="cnt" style="color:red;">30</span> Seconds
In javasccript function start the timer and call refresh after 30sec.
function checkboxClicked() {
//function gets called when the checkbox is clicked and the counter starts
let counter = 30
window.setInterval(function() {
counter--;
if (counter >= 0) {
var span;
span = document.getElementById("cnt");
span.innerHTML = counter;
}
if (counter === 0) {
clearInterval(counter);
}
}, 1000);
window.setInterval('refresh()', 30000);
}
// REFRESH OR RELOAD PAGE.
function refresh() {
window.location.reload();
}

Related

Why isn't my code running before the interval completes?

In the snippet, I want the color of timer to change to red before the alert pops up.
I have written $("#timer").css('color', 'red'); before alert("Time Up!"), so logically it should change the text color before showing the alert, but it is changing color after displaying the alert.
let time = 3;
$(function() {
let interval = setInterval(function() {
time--;
if (time >= 0)
document.getElementById("timer").innerHTML = time + "";
else {
$("#timer").css('color', 'red');
clearInterval(interval);
alert("Time Up!")
}
}, 1000);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="timer">3</h1>
The issue is because the alert() blocks the UI from updating, and although you call css() before alert(), there's not enough time to update the DOM before the alert appears and temporarily prevents any further rendering.
To fix this, place the alert() call in a timeout with a short delay. This allows the UI to be updated before the alert() is displayed:
let time = 3;
jQuery($ => {
let interval = setInterval(function() {
time--;
if (time >= 0) {
$("#timer").html(time);
} else {
$("#timer").css('color', 'red');
clearInterval(interval);
setTimeout(() => alert("Time Up!"), 0);
}
}, 1000);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="timer">3</h1>

Autostart Countdown Timer in button

I am trying to implement a countdown timer into my page to show when the page will be redirect to google.com. So far i have create a button but it will only start counting when i clicked it. Is it possible to make the button auto start countdown when i access to that page?
<button id="myButton" class="butstyle" style="float:right">Click To Redirect</button>
<script>
var counter = 10;
$('.butstyle').on('click',function(e){
e.preventDefault();
e.stopPropagation();
if($(this).hasClass('butstyle')){
$('.butstyle').text('You will be redirected in: 10 seconds');
$(this).removeClass().addClass('butAfter');
var int = setInterval(function() {
counter--;
$('.butAfter').text('You will be redirected in: '+counter+' seconds');
if (counter == 0) {
clearInterval(int);
counter = 10;
window.location.href = "https://www.google.com";
//do your next action here:
}
}, 1000);
}
});
</script>
You can switch your button on click function with document ready like this:
$( document ).ready(function() {
// Put relevant code here
}
Use this. This will automatically clicks on you button with this part of code
$(document).ready(function() {
$(".butAfter").trigger("click");
});
And Counter starts.
Final code:
$(document).on("click", ".butAfter", function(e) {
e.preventDefault();
e.stopPropagation();
if ($(this).hasClass('butstyle')) {
$('.butstyle').text('You will be redirected in: 10 seconds');
$(this).removeClass().addClass('butAfter');
var int = setInterval(function() {
counter--;
$('.butAfter').text('You will be redirected in: ' + counter + ' seconds');
if (counter == 0) {
clearInterval(int);
counter = 10;
window.location.href = "https://www.google.com";
//do your next action here:
}
}, 1000);
}
});
$(document).ready(function() {
$(".butAfter").trigger("click");
});
var counter = 10;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton" class="butstyle butAfter" style="float:right">Click To Redirect</button>

Pause countdown timer (JavaScript)

I want the countdown timer to pause when I click the pause button, and start from where it left off when I click the go button. It'd also be good if the go button enables again when reset is clicked, but as of now it continues being disabled for as long as the timer was set.
For pausing, I tried what I saw in this fiddle but it didn't work. I also tried this to no avail:
$("#pause").click(function() {
clearInterval(count());
})
Here's the fiddle.
Thanks!
Here you have solution of working countdown: http://jsfiddle.net/XcvaE/4/
<script>
var CCOUNT = 60;
var t, count;
function cddisplay() {
// displays time in span
document.getElementById('timespan').innerHTML = count;
};
function countdown() {
// starts countdown
cddisplay();
if (count == 0) {
// time is up
} else {
count--;
t = setTimeout("countdown()", 1000);
}
};
function cdpause() {
// pauses countdown
clearTimeout(t);
};
function cdreset() {
// resets countdown
cdpause();
count = CCOUNT;
cddisplay();
};
</script>
<body onload="cdreset()">
<span id="timespan"></span>
<input type="button" value="Start" onclick="countdown()">
<input type="button" value="Stop" onclick="cdpause()">
<input type="button" value="Reset" onclick="cdreset()">
</body>

Javascript auto page refresh code

this is the code that comes in head section and it will automatically refresh the whole page in 1 min as i put 6000 in the code below
<script type="text/javascript">
setTimeout('window.location.href=window.location.href;', 6000);
</script>
is there any way for example, when there's 10 seconds left to refresh the page then, a button will display and say "Click here to reset timer" and it will reset that timer to 1 min again?
<script language="javascript">
var timeout,interval
var threshold = 15000;
var secondsleft=threshold;
startschedule();
window.onload = function()
{
startschedule();
}
function startChecking()
{
secondsleft-=1000;
if(secondsleft <= 10000)
{
document.getElementById("clickme").style.display="";
document.getElementById("timercounter").innerHTML = Math.abs((secondsleft/1000))+" secs";
}
}
function startschedule()
{
clearInterval(timeout);
clearInterval(interval);
timeout = setTimeout('window.location.href=window.location.href;', threshold);
secondsleft=threshold;
interval = setInterval(function()
{
startChecking();
},1000)
}
function resetTimer()
{
startschedule();
document.getElementById("clickme").style.display="none";
document.getElementById("timercounter").innerHTML="";
}
</script>
Please wait...<span id="timercounter"></span>
<button id="clickme" style="display:none;" onclick="javascript:resetTimer();">Click here to reset timer</button>
Assuming you have the following html for the button:
<button id="cancel-reload-button" style="display: none" onclick="cancelReload()">Cancel Reload</button>
And this as the script (Note: this gives the idea, but is not neccesarily fully tested):
// Variable for holding the reference to the current timeout
var myTimeout;
// Starts the reload, called when the page is loaded.
function startReload() {
myTimeout = setTimeout(function() {
document.getElementByID("cancel-reload-button").style.display = "inline";
myTimeout = setTimeout(function() {
window.location.reload();
} 10000)
}, 50000);
}
// Cancel the reload and start it over. Called when the button is
// clicked.
function cancelReload() {
clearTimeout(myTimeout)
startReload()
}
// On page load call this function top begin.
startReload();
I created two functions, one for starting the reload and the second one for cancelling it.
Then I assigned the timeout to the variable myTimeout which can be used to later cancel the timeout.
Then I called myTimeout twice - Once for 50 secs, at which point it shows the button and once for 10 secs after which it finally reloads.
How about below? If you click on OK to reset timer, it would keep giving the confirm box every 50 seconds. If you click cancel, it will refresh the page in 10 seconds.
setInterval(function(){ var r = confirm("Reset Timer");
if (r == true) {
setTimeout('window.location.href=window.location.href;', 60000);
} else {
setTimeout('window.location.href=window.location.href;', 10000);
}
}, 50000);
Note: In your question you specified 1 minute, but your code works for 6 seconds(6000 -- > 6 seconds not 60 seconds) I have included for a minute
You can use 2 setTimeout calls, one to make the "Reset" button show up and another one for the refresh timer reset. The trick is to store the second setTimeout on a global variable and use clearTimeout to reset it if the button is pressed.
Here is some JavaScript code to illustrate:
<script type="text/javascript">
var autoRefreshTime = 30 * 1000; // 60000ms = 60secs = 1 min
var warningTime = autoRefreshTime - (10 * 1000); // 10 secs before autoRefreshTime
waitTimeout = setTimeout('window.location.href=window.location.href;', autoRefreshTime);
warningTimeout = setTimeout('ShowResetButton();', warningTime);
function ShowResetButton() {
// Code to make the "Reset" button show up
}
// Make this function your button's onClick handler
function ResetAutoRefreshTimer() {
clearTimeout(waitTimeout);
waitTimeout = setTimeout('window.location.href=window.location.href;', autoRefreshTime);
}
</script>
The way I would do it is make a function with a timeout, and invoke that function
<script type="text/javascript">
var refreshFunc = function(){
setTimeout(function(){
var r = confirm("Do you want to reset the timer?");
if(r === false){
window.location.href=window.location.href;
}else{
refreshFunc();
}
}, 6000);
};
refreshFunc();
</script>
One big problem with using confirm in this case is you cannot program it to reject. You would have to implement you own modal/dialog box so you can auto reject in 10 seconds.
Try using setInterval():
var time;
$(function() {
time = $('#time');
$('#reset').on('click', reset);
start();
});
var timer, left;
var start = function() {
left = +(time.text()); //parsing
timer = setInterval(function() {
if (0 <= left) {
time.text(left--);
} else {
clearInterval(timer);
location.replace(location);
}
}, 1000);
};
var reset = function() {
if (timer) {
clearInterval(timer);
}
time.text('59');
start();
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h1><span id='time'>59</span> second(s) left</h1>
<input id='reset' value='Reset' type='button' />

ASP.NET MVC5, creating a timer for quiz using javascript

Here is the code I use, I can't figure out why at 0 seconds, the form won't submit to the thank you page. I am trying to call the submit button from the #using (htmlbeginform()) statement. Please help.
<form name="counter">
<input type="text" size="8"
name="d2">
</form>
<script type="text/javascript">
var minutes = 1
var seconds = 00
document.counter.d2.value = '30:00'
function display()
{
if (seconds <= 0)
{
minutes -= 1
seconds += 59
}
if (minutes <= -1)
**{
$(document).ready(function () {
setTimeout(function () { nextQuestion() }, 5000);
$("#questionform").submit(function () {
alert("Submit after 5 second.");
});
});
function nextQuestion() {
$("#questionform").trigger("submit");
}
}** **PART of code in between ** is where I am having trouble, cant figure out what is wrong**
else
seconds -= 1
document.counter.d2.value = minutes + ":" + seconds
setTimeout("display()", 1000)
}
display()
</script>
#using (Html.BeginForm("ThankYou", "Questions", FormMethod.Post, new { #id = "questionform" }))
{
#Html.EditorFor(x => x.Questions)
<input type="submit" id="submit" class="btn btn-default" value="Submit" />
}
TRYING TO USE THIS BUTTON DOWN HERE to SUBMITAT ZERO SECONDS
the $(document).ready() event triggers only when your document is fully loaded,
since you attach this event after the document is loaded, this will never trigger.
you have to do it in this way:
function nextQuestion() {
$("#questionform").trigger("submit");
} //it's better declare your functions outside an if statment
if (minutes <= -1) {
setTimeout(function () { nextQuestion() }, 5000);
$("#questionform").submit(function () {
alert("Submit after 5 second.");
});
/*if you submit,
the page changes and this alert will never appear*/
});
}

Categories

Resources