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.
Related
Please I want to create a button that can be clicked only once in 24hrs in js but I don't really know how to put it up.
<html>
<head>
<title>Disable Button</title>
<script>
function doSomething () {
document.getElementById("myButton").disabled = true;
document.getElementById("myButton").disabled = false;}
</script>
</head>
<body>
<input type="button" id="myButton" onclick="doSomething()"
value="Click Here To Do Something"/>
</body>
</html>
window.onload = () => {
//on load of the page it will check for same day and disable/enable.
let lastclicked = localStorage.getItem('lastclicked') || '';
document.getElementById("myButton").disabled = lastclicked === new Date().toDateString();
}
function doSomething () {
localStorage.setItem('lastclicked', new Date().toDateString());
document.getElementById("myButton").disabled = true;
}
you need to save to date and time of the last trigger somewhere in local storage or cookies so next when the button is triggered it checked the date in storage if that exists then it will check the date.
hope so it will work for you.
var todayclick = true;
var buttonval = document.getElementById("myButton");
buttonval.click(function() {
if (todayclick ) {
alert("Error!");
}
else {
variable += 1;
todayclick = false;
}
setTimeout(function() {
todayclick = true;
}, 86400);
});
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
}
This question already has answers here:
setTimeout calls function immediately instead of after delay
(2 answers)
Closed 1 year ago.
i want you to have to hold the button down for a second for it to start...
I've tried a couple of things like
function startHold1() {
setTimeout(function(){
startHold1A = setInterval(func1(), 250) }, 1000)
}
function endHold1() {
setTimeout(function(){
clearInterval(startHold1A, 950)
})
}
func1 basically adds 1 to a variable and displays it on the screen also i have a button that initiates startHold1 onmousedown and endHold1 onmouseup
I'm a super noob at code please help!
var setint = '';
$(document).ready(function() {
var val = 0;
$('#hold').on('mousedown',function (e) {
clearInterval(setint);
val = 0;
setint = setInterval(function () {
$("#putdata").val(++val);
console.log("mousehold");
},50);
});
$('#hold').on("mouseleave mouseup", function () {
val = 0;
$("#putdata").val(val);
clearInterval(setint);
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="putdata" />
<input type="button" value="mouse-hold" id="hold" />
</body>
<html>
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);
I'm using Keith Wood's jQuery Countdown timer. http://keith-wood.name/countdown.html
What I want to achieve is a countup with stop and resume buttons, and controls to add and subtract minutes and seconds:
I create a countup (from 0 to 60 minutes) and pause it right away, like this:
$('#contador_tiempo').countdown({
since: 0,
format: 'MS',
layout: '{mnn}{sep}{snn}'
});
$('#contador_tiempo').countdown('pause');
But it seems that it's still running in the background. When I click the buttons to add or subtract, the functions do the operations on top of that background counter, not the displayed counter.
Full code on JSFiddle, with the behaviour reproduced:
http://jsfiddle.net/J2XHm/4/
(Play a bit with the controls and you will see that it keeps counting although it's paused.)
Yes, there is a bug in the 'getTimes' command - it recalculates when paused. I'll make the correction in the next release (1.6.2) but in the meantime you can change the _getTimesPlugin function:
_getTimesPlugin: function(target) {
var inst = $.data(target, this.propertyName);
return (!inst ? null : (inst._hold == 'pause' ? inst._savePeriods : (!inst._hold ? inst._periods :
this._calculatePeriods(inst, inst._show, inst.options.significant, new Date()))));
},
If you can accept lightweight code, i.e. without using the jQuery countdown timer, the following might help you:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://localhost/web/JavaScript/jQuery/jquery"></script>
<script type="text/javascript">
var countUpSeconds = 0;
var interval = null;
function displayTime() {
$("#timeContainer").text(format(Math.floor(countUpSeconds/60))+":"+format(countUpSeconds%60));
}
function playStop() {
if(interval) {interval=window.clearInterval(interval);}
else {interval = window.setInterval(countUp, 1000);}
}
function countUp() {
++countUpSeconds;
if(countUpSeconds >= 3600) {/* do something when countup is reached*/}
displayTime();
}
function format(s) {return s<10 ? "0"+s : s;}
$(function() {
displayTime();
$("#playStop").on("click", function () { playStop(); } );
$("#addMin").on("click", function () { countUpSeconds += 60; displayTime(); } );
$("#subMin").on("click", function () { countUpSeconds = Math.max(0, countUpSeconds-60); displayTime(); } );
$("#addSec").on("click", function () { countUpSeconds += 1; displayTime(); } );
$("#subSec").on("click", function () { countUpSeconds = Math.max(0, countUpSeconds-1); displayTime(); } );
});
</script>
</head>
<body>
<div id="timeContainer"></div>
<button id="playStop">Play/Stop</button>
<button id="addMin">+1 minute</button>
<button id="subMin">-1 minute</button>
<button id="addSec">+1 second</button>
<button id="subSec">-1 second</button>
</body>
</html>