I have a full ajax application. i am using the below code to update time every minute. But if i keep the browser open for >10 min the browser becomes non responsive/slow. Suggest a better code.
function tick()
{
var d = new Date();
var time = padNumber(d.getHours(),2)+':'+padNumber(d.getMinutes(),2);
$('#WeatherBoLfTime').html(' '+time);
t = setInterval('tick()',60000);
}
$(document).ready(function(){
tick();
})
The problem is that you're calling setInterval many times and never clearing any of them. So after a while you have lots of interval callbacks running at around the same time.
Change
t = setInterval('tick()',60000);
to
t = setTimeout(tick,60000);
When I first started out coding JavaScript I took down a Lycos web server with AJAX calls because I made the same mistake :-)
Note that since you're displaying the actual time, you should use a much shorter timer than 1 minute. If I land on your webpage at 13:42:30, the time will not be updated until ~13:43:30. To keep it in sync with the machine's time, you would probably want to set the timer for 1000.
setInterval() sets an interval. You only need to set it up once, it will get called every 60000ms automatically. setTimeout() is the one you have to setup every time again.
As others have pointed out, you are creating new interval every time.
Move it to outside your function.
function tick()
{
var d = new Date();
var time = padNumber(d.getHours(),2)+':'+padNumber(d.getMinutes(),2);
$('#WeatherBoLfTime').html(' '+time);
}
$(document).ready(function(){
t = setInterval(tick,60000);
})
Edit: I'm slow and other answers seem to be updated. So this one is useless now :)
Have look in below demo code, which will be updated each second...
<!DOCTYPE html>
<html>
<head>
<title>j</title>
<script type="text/javascript">
function myFunction()
{
setInterval(function(){
var d = new Date();
document.getElementById("dates").innerHTML = new Date(d.getTime());}, 1000);
}
</script>
</head>
<body>
<input type="button" name="e" onclick="myFunction()">
<p id= "dates">ok</p>
</body>
</html>
Related
I have a simple question maybe, I was for days looking for solution and don't want to waste your time, but isn't work for me so I'm here now.
Im using P5JS, and I wanted to create auto click function.
There how I call an button in sketch.js file
var button1 = createButton("Generator");
button1.mousePressed(banana);
button1.id('autoclick');
Here you can see how I call in index.html
Im trying something like this:
<script type="text/javascript">
var iteration = true;
var time = new Date();
var delay = 5000; // 5 secondes
while(iteration) {
if(time.getTime() + 5000 < new Date().getTime()) {
iteration = false;
}
}
document.getElementByID('autoclick').click();
// noprotect
</script>
Maybe I complicate to much? any suggetions? thank you!
Your while loop is blocking, which means that while Javascript is running your while loop, it will not be able to execute any other code. You want to use setInterval() for your purposes.
For example,
setInterval(() => console.log("hello!"), 1000)
I implemented a simple countdown timer using window.setInterval. It works perfectly in my desktop browser but it does not work correctly on my smartphone (Fairphone 2) as a PhoneGap/Cordova app. According to my examinations and my research on the internet the interval/timeout is interrupted when the phone is sent to sleep/standby. That's why it does not work.
Astonishingly the interval/timeout is not interrupted when my phone is connected via usb cable to my computer. So probably it's an energy-saving feature that's causing the bad behaviour.
So, I'm lost. I don't know how to implement my simple countdown timer which of course should also work when the phone sleeps (=display turned off). Is there an alternative for window.setInterval() / window.setTimeout() ?
Here is my simple code (as stated: window.setTimeout does not work, either):
...
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/libs/jquery.js"></script>
<script>
var min = 25;
$(document).ready(function(){
intervalID = window.setInterval(function () {
--min;
if (min > 0) {
$("#countdown").text(min);
}
}, 6000);
});
</script>
...
<p id="countdown">0m</p>
Use the interval timer only for updating the display. Use the system time to decide what to display.
Then, if your interval doesn't get called when the display is not visible, this is no problem. The next time it does get called (when the display is turned on again), it will calculate the correct elapsed time from the system time and it will display correctly.
For this reason (and several others), you should never assume that setInterval() is going to keep perfect time. In Javascript, it just means you want to be called every once in a while and you get to set an approximate time to specify the frequency, but the interval may be shut off for long periods of time.
Get the time when your interval starts with Date.now() and then each time the interval fires, get the new system time and subtract from the start time to see how much time has elapsed and then calculate what you want to display.
If you want to show minutes remaining on a 25 minute timer, you could do this:
function showTimer(selector, minutes) {
var startTime = Date.now();
var interval;
function showRemaining() {
var delta = Date.now() - startTime; // milliseconds
var deltaMinutes = delta / (1000 * 60);
if (deltaMinutes < minutes) {
// display minutes remaining
$(selector).text(Math.round(minutes - deltaMinutes));
} else {
$(selector).text(0);
clearInterval(interval);
}
}
interval = setInterval(showRemaining, 15 * 1000);
showRemaining();
}
$(document).ready(function(){
showTimer("#countdown", 25);
});
Working demo: https://jsfiddle.net/jfriend00/807z860p/
I found a cordova plugin which executes timeouts/intervals even when the display is turned off:
cordova-plugin-timers (on github)
The answer of jfriend00 was also helpful.
I am creating time that i will use to make a countdown timer later. Its easy to create when only JavaScript or jQuery is my choice. But the problem comes when i get the PHP date time string and display it using jQuery. It does not dynamically update the time after using the PHP date and time string. Below is a little code of mine.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var value = $("#date_time").text();
function countdown(){
setTimeout(countdown, 1000);
var date = new Date(Date.parse(value));
$("#php_date_time").text(date);
}
countdown();
});
</script>
</head>
<body >
<div id="date_time"><?php echo Date("d-m-Y H:i:s");?></div>
<div id="php_date_time"> </div>
</body>
</html>
The code works perfectly fine if i do not pass PHP date time string to javascript Date() function as an argument. If starts working, i can make countdown myself.
var date = new Date(); // works fine without passing php date time string
var date = new Date(Date.parse(value)); // this does not work fine. Time does not update
Please help suggest what i need to do.
Thanks.
Since you want it to start from time that PHP gives you you need to change your javascript to use that time to set initial value and then change that each second. Now you're just updating with same value.
http://codepad.viper-7.com/sPVlEI
$(document).ready(function(){
var value = $("#date_time").text(); //get init value
var date = new Date(Date.parse(value)); //store initial time
setInterval(function countdown(){
$("#php_date_time").text(date); //set time
date = new Date(date.getTime() + 1000); //create new time from old + 1 sec
},1000); // will call countdown() function every second
});
The problem is as the server compiles your php date just once, your countdown function always uses the same date value. there is another issue that you have to consider which is your server time doesn't necessary match with client time. you'd better start your timer with client time. but if you want to start it based on your server time, try this and your problem is solved:
$(document).ready(function(){
var value = $("#date_time").text();
function countdown(date){
setTimeout(function(){
countdown(new Date(date.valueOf()+1000));
}, 1000);
$("#php_date_time").text(date);
}
countdown(new Date(Date.parse(value)));
});
I am working on rails and written javascript code for displaying timer that starts from 00:00:00.
[NOTE: i have two button start and stop for starting the timer and stopping the timer]
function timer(){
var sec, min, hour;
sec=0;
min=0;
hrs=0;
sec++;
if(sec>=60){
min++;
sec=0;
}
if(min>=60){
hrs++;
min=0;
}
document.getElementById("hrs").innerHTML=hrs;
document.getElementById("min").innerHTML=min;
document.getElementById("sec").innerHTML=sec;
setTimeout(timer(), 1000);
}
Now this is working fine in my rails web application. But if I will redirect to another page and return to this page I am losing the timer value.
Here, I want the clock to be running continuously after page redirect also.
How to fix this?
get the timestamp... save it somewhere and pass it as a variable to the next page
var start=new Date().getTime();
to get the time passed
var currentMillisecondsPassed=new Date().getTime()-start;
convert this to hh:mm:ss.msec or whatever...
the next page needs just the start value and there are many ways to pass it..
php,js,get,post....and manymany more.
setTimeout() is also not precise for timers.
here is an example passing the value with querystring..
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>timer</title>
<script>
window.onload=function(){
var pt=window.location.search.split('=')[1],
e=document.body.childNodes,
t=e[0],
s=(pt*1||0),
interval,
ms2Time=function(a) {
var ms=parseInt((a%1000)/100),
s=parseInt((a/1000)%60),
m=parseInt((a/(1000*60))%60),
h=parseInt((a/(1000*60*60))%24);
return (h<10?'0'+h:h)+':'+(m<10?'0'+m:m)+':'+(s<10?'0'+s:s)+'.'+ms;
},
Start=function(){
s=new Date().getTime();
interval=window.setInterval(getcurrent,100);
},
Stop=function(){
window.clearInterval(interval);
s=0;
},
getcurrent=function(){
t.textContent=ms2Time(new Date().getTime()-s);
},
changepage=function(){
window.location='?start='+s;
};
e[1].addEventListener('click',Start,false);
e[2].addEventListener('click',Stop,false);
e[3].addEventListener('click',changepage,false);
if(pt&&pt!=0){
interval=window.setInterval(getcurrent,100);
}
}
</script>
</head>
<body><div id="timer"></div><button>start</button><button>stop</button><button>anotherpage</button></body>
</html>
as i said... you can store the start value anywhere ...so if you have any preferences ... just tell me and i can change the code for u.
Because you are redirecting, a java-script timer won't do. You should use system time instead. You can take some help from session variables while redirecting from the page, to save the time stamp when the timer started.
You can set the initial values for the variables sec, min, hour using session or cookies. And include this file in all the pages which you want the timer should run in background.
function timer(){
sec++;
if(sec>=60){
min++;
sec=0;
}
if(min>=60){
hrs++;
min=0;
}
setTimeout(timer(), 1000);
}
And add the values to the DOM only in the page which you are showing the timer.
Try to send default sec, min and hrs values from server, e.g. save them in coockie.
Basically, I am designing a quiz application with limited time. Use selects answer to a question and the next question loads using an Ajax request. All questions must be answered within a time frame of, say 2 minutes.
A clock ticks away to show how much time is left and as soon as it hits 0, results are shown. Now since the timer will be implemented using window.setTimeout(), it is possible that the value of timer variable be modified using an external bookmarklet or something like that. Anyway I can prevent this? I think this is implemented on file sharing sites like megaupload. Any forgery on the timer variable results in request for file being rejected.
Have .setTimeout() call an AJAX method on your server to synch time. Don't rely on the client time. You could also store the start time on the server for a quiz, and then check the end time when the quiz is posted.
You need to add a validation in your server side. When the client want to load the next question using an Ajax request, check whether deadline arrived.
The timer in client side js just a presention layer.
If the function runs as a immediately called function expression, then there are no global variables and nothing for a local script to subvert. Of course there's nothing to stop a user from reading your code and formulating a spoof, but anything to do with javascript is open to such attacks.
As others have said, use the server to validate requests based on the clock, do not rely on it to guarantee anything. Here's a simple count down that works from a start time so attempts to dealy execution won't work. There are no global variables to reset or modify either.
e.g.
(function (){
// Place to write count down
var el = document.getElementById('secondsLeft');
var starttime,
timeout,
limit = 20; // Timelimit in seconds
// Function to run about every second
function nextTick() {
var d = new Date();
// Set start time the first time
if (!starttime) starttime = d.getTime();
var diff = d.getTime() - starttime;
// Only run for period
if (diff < (limit * 1000)) {
el.innerHTML = limit - (diff/1000 | 0);
} else {
// Time's up
el.innerHTML = 0;
clearTimeout(timeout);
}
}
// Kick it off
timeout = window.setInterval(nextTick, 1000);
}());