How can I make a function, and have it run/refresh every (second) once in a while based on a timer? I'm trying to run a function and it needs to be updated to check if a parameter is checked.
function checkTime() {
if(document.getElementById("time").innerHTML === "12:00:00 PM") {
alert("It's noon!");
}
}
This can be accomplished by using setInterval(). I am using something similar for this; I made a timer that shows the time that my period ends (in school) and also shows the current time, and when the time matches the period ends time, it should change to the next period automatically. With your example, you can do something like this:
//init function
function checkTime() {
//check if its noon
if(document.getElementById("time").innerHTML === "12:00:00 PM") {
//alert
alert("It's noon!");
}
}
//set the interval
setInterval(function() {
//execute code
checkTime();
}, /* every 5 seconds, or 5000 milliseconds */ 5000);
Related
var seconds_lapsed = 0;
function tick() {
seconds_lapsed++;
}
function countup() {
setTimeout(function () {
if (stopped) return; // stop the loop
if (!is_paused()) {
tick();
show_time_left();
}
countup(); // <--- this is the "loop"
}, 1000);
}
This is the core of my timer. Of course I have some view to represent the result. But ticking is done here.
The problem
It shows wrong time. Have a look at this:
The timer was set for 3 hours. Twelve minutes lapsed. And the discrepancy is almost 1.5 minutes.
In the other window the timer by Google is working. This one:
So, I just compared my timer with that of google. I started them almost at once. The difference should be no more than a couple of seconds (to switch the window and press the button).
What is the reason for this, and how can I correct it?
setTimeout with an interval of 1000 does NOT run exactly after every 1 seconds.
It schedules to run after 1 second, but can be delayed with by actions running at that time.
A better way of solving this is by calculating via date difference.
I took your sample (added the missing vars/funcs) and changed the tick() function to use date diffs.
var seconds_lapsed = 0;
var startDateTime = new Date();
var stopped = false;
var is_paused = function() { return false; }
function tick() {
datediffInms = new Date() - startDateTime;
seconds_lapsed = Math.round(datediffInms / 1000);
}
function countup() {
setTimeout(function () {
if (stopped) return; // stop the loop
if (!is_paused()) {
tick();
//show_time_left();
console.log(seconds_lapsed)
}
countup(); // <--- this is the "loop"
}, 1000);
}
countup();
Hi Everyone I know it is basic and silly to ask but this question is eating me up .
If I have a below following code .
var timerVal = 900000
function myFunction() {
setTimeout(function(){ alert("Hello"); }, timerVal);
}
myFunction()
As per the above code an alert will come at 15 mins . But after ten minutes I thought to extend it for more 5 mins by changing the value of timerVal to 1200000. Now would the alert will come after another 10 mins . i.e. total 20 mins after the alert will come or it will come after 15 mins of the completion .
Suppose the code is like this :
var timerVal = 900000
function myFunction() {
setTimeout(function(){ alert("Hello"); }, timerVal);
}
function change(){
setTimeout(function(){
timerVal = 1200000;
},60000);
}
myFunction();
change();
Can Anyone give let me know what will be the result and brief description why ?
The result will be that the timer will be executed at the 900000 millisecond mark, although you have tried to change it to 1200000 millisecond by changing the value of the timerVal variable.
This is because in JavaScript it is pass by value and since you have passed 900000 initially, the timer is already queued at 900000 and hence cannot be altered by changing the value of the timerVal variable again.
So this code, is simply making the timerVal point to the new number 1200000 not really changing the timeout set earlier:
function change(){
setTimeout(function(){
timerVal = 1200000; //timerVal reference is pointing to a new number
}, 60000);
}
To really change the timer behavior you need to clear the timeout using the id returned by the setTimeout call and create another one with the new timeout value.
let timerVal = 9000;
function myFunction() {
return setTimeout(function(){ alert("Hello"); }, timerVal); //returning the id
}
function change(id, newVal){
clearTimeout(id); //clearing the previous timer using the id
setTimeout(function(){ alert("Hello"); }, newVal);
}
let id = myFunction();
change(id, 5000);
Well, in general to be able to "extend" a timer, you'll need to cancel it (using clearTimeout), and re-create it. For this you'll need to keep track of how long has elapsed since it originally started and calculate a new time.
The code below demonstrates a function extendableTimeout which you can use like the normal setTimeout, except it returns an object with an extend function you can use for your purpose.
The demo has 2 button, the first starts an action delayed for 5s. Clicking the extend button extends the timeout by another 5 seconds. You can compare clicking the extend or not to see the timings.
function extendableTimeout(fn, time){
var id = setTimeout(fn, time);
var timeStart = new Date();
return {
timerId: id,
extend: function(time){
clearTimeout(id);
var elapsed = new Date() - timeStart;
var newTime = time - elapsed;
setTimeout(fn,newTime);
}
}
}
var myTimer;
$('#start').on("click", function(){
console.log("Started at " + new Date());
myTimer = extendableTimeout(() => console.log("Finished at " + new Date()), 5000);
})
$("#extend").on("click", function(){
myTimer.extend(10000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="start">Start</button>
<button id="extend"> + 5s </button>
AFAIU, you cannot extend the time of a setTimeout. What you can do is stopping it from executing, and create another setTimeout with the new value. Like this:
var timer = setTimeout(()=>console.log("first"), 2000);
clearTimeout(timer);
var timer = setTimeout(()=>console.log("second"), 2000);
You cannot extend it because the timer is created with the value the variable had at the time of creation event. It's not a reference that can be evaluated from time to time. It's a fixed value that is evaluated only on creation time.
I'm doing a simple script for detecting when it's 12 o'clock, that it shows a certain div, if not that it remains hidden. So the general idea is this:
function displayDiv() {
d = new Date();
if(12 === d.getHours()){
idMain.style.display = 'block';
} else {
idMain.style.display = 'none';
}
}
But I want that in an event listener so when it's that hour it automatically displays the div or hides it. Something like:
document.addEventListener(d.getHour() === 12, displayDiv);
Or something like that but I don't know how to establish the parameters to get the desired response or for it to work.
Thanks
You can use a setInterval to run the function every minute (60000 milliseconds).
function displayDiv() {
d = new Date();
if(12 === d.getHours()){
idMain.style.display = 'block';
} else {
idMain.style.display = 'none';
}
}
setInterval(displayDiv, 60000);
I completely agree with Hev1 solution of using the setInterval (use his implementation). Here is some additional information though:
setInterval takes 2 arguments. The first argument is the callback function which you want to execute at a specific time interval. And the second argument is the amount of miliseconds you want the function to execute.
Also I want to point out if you ever are in need of clearing the interval there is also a function for this call clearInterval. You have to store the interval in an variable for this, here is an example:
const myInterval = setInterval(increase, 1000);
let index = 5;
function increase() {
if (index === 0) {
clear();
} else {
console.log(index);
index--;
}
}
function clear() {
clearInterval(myInterval);
console.log('interval cleared');
}
After the interval is stored in a variable the clear() method gets called when the interval reaches 0. In the clear function clearInterval is called to remove the interval.
We can put the if condition using following current time values.
var dates = new Date();
var hours = dates.getHours(); var minutes = dates.getMinutes();
I'm trying to create an if statement which sets a timeout when a function is called:
var timeOutID;
if (//function1 is called) {
timeOutID = setTimeout(function1, 30000);
}
The idea is that the function gets repeatedly called after 30 seconds, but the timeout can be reset at any point if function is called (e.g. a button is clicked). How can this be accomplished? Many thanks.
When you want to do something repeating at a set interval, setInterval may be a better way to go. It will call a method after every X milliseconds if you don't cancel it.
Here is a basic example of reseting the interval whenever a button is clicked. In the log you will see that when you don't click the button a new log line appears every 5 seconds. When you click on the button the next line will take longer to appear after which they will appear again every 5 seconds.
I used 5 seconds instead of 30 so you don't have to wait that long to see the effect of pressing the button.
const
resetButton = document.getElementById('reset'),
confirmationMessage = document.getElementById('confirmation'),
intervalDuration = 5000;
let
intervalId = null
lastCallTime = new Date();
function resetInterval() {
// Stop the current interval...
clearInterval(intervalId);
// and start a new interval.
startInterval();
}
function startInterval() {
// Set an interval, it will call logTimeSinceLastCall every X seconds.
intervalId = setInterval(() => {
logTimeSinceLastCall();
}, intervalDuration);
}
function logTimeSinceLastCall() {
// Hide the message that the interval has been reset.
confirmationMessage.classList.add('hidden');
const
// Get the current time.
now = new Date(),
// Substract the time from the last call, the difference is the number of milliseconds passed.
diff = now.getTime() - lastCallTime.getTime();
// Log a line to the console for some visual feedback.
console.log(`Last call was ${diff}ms ago`);
// Update the time stamp of the last time this method was called.
lastCallTime = now;
}
function onResetClicked(event) {
resetInterval();
// Show the message that the button has been clicked.
confirmationMessage.classList.remove('hidden');
}
// Whenever the button is clicked, reset the interval.
resetButton.addEventListener('click', onResetClicked);
// Start the initial interval.
startInterval();
.hidden {
display: none;
}
<button type="button" id="reset">Reset interval</button>
<p id="confirmation" class="hidden">
The interval has been reset.
</p>
I have three function: the first is a clock with setTimeout within, the second is a function called when the clock reach zero with a setInterval within and the third is a function called when the setInterval of the second is cleared and set another interval that when is cleared call the clock again. The chain of functions work but accelerate the clock a lot and I don't know why.
var secs=8;
function clock(){
secs--;
var timer=setTimeout(clock,1000);
document.getElementById('clock').innerHTML = 'Clock: ' + secs;
if(secs==0){
clearTimeout(timer);
noEvent();
}
}
function noEvent(){
var count=10;
var timer1=setInterval(function(){
// do something
count--;
if(count==0){
clearInterval(timer1);
repetition();
}
},200)
}
function repetition(){
var count=3;
var timer2=setInterval(function(){
// do something
count--;
if(count==0){
clearInterval(timer2);
secs=8;
clock();
}
},1000)
}
var index=0;
$("myId").click(function(){
var rand=this.id;
var check=(arrComputer[index]==rand); // arrComputer is an array
// generated by the computer
// by other function
if(check==true) {
// do something
clock();
}
}
The functions and the calls work but the clock that is set to 1 second (setTimeout(clock,1000)) go to one second in the first call, but in successives go much faster, so the variable secs go 8,7,6,5,...,0 but to a bigger speed: between 8 and 7 there is not 1000ms but may be 200ms.