Putting a setInterval when a function called - javascript

var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 1, 20, 00, 0) - now;
function openAPage() {
var startTime = new Date().getTime();
var myWin = window.open("http://google.com","_blank")
var endTime = new Date().getTime();
var timeTaken = endTime-startTime;
document.write("<br>button pressed#</br>")
document.write(startTime);
document.write("<br>page loaded#</br>")
document.write(endTime);
document.write("<br>time taken</br>")
document.write(timeTaken);
myWin.close()
}
function beginSequence() {
openAPage();
setInterval(openAPage, 5000);
}
setTimeout(beginSequence, millisTill10);
This is my JS code. I am opening a web page with setTimeout as you see. But after then I want to put an internal for example I will call openAPage function every 1 minute after setTimeout statement. How will I do it? Can anyone fix my code?

setTimeout(startOpeningPages, millisTill10);
function startOpeningPages() {
openAPage();
setInterval(openAPage, 60 * 1000);
}

I realize there are a lot of correct answers already. I'll post this anyway for kicks :)
function() {
var win = window.open("about:blank")
var doc = win.document
doc.write("Hello")
setTimeout(arguments.callee, 60*1000)
}()
These are 2 of the my favorite things you can do in Javascript: Self-invoke a function (the ending () after the function declaration, and being able to access the anonymous function from within the function through arguments.callee.
This is better than setInterval in that the first process has to be completed and then 60s later, the second process starts. With setInterval, the process just keeps starting every 60s. 60s is a large interval where this wouldn't matter as much, but this usually matters a lot more with smaller times (in the ms ranges). Because it might end up buffering the second function to execute before the first one is complete.

Related

Avoiding Infinite Loops

I'm quite a newbie, so forgive my ignorance. I am trying to, through local storage, get a timer to tell the user when they last visited the page. But I have instead made an infinite loop, how do I correct this? calling the function outside the function? What would this look like?
$(document).ready(function(){
var myDate = new Date(2015,4,9,0,0);
localStorage["mydate"] = JSON.stringify(myDate);
startTimer();
});
function startTimer() {
setInterval(function(){
var text = "It's been " + hoursSinceFirstVisit() + " hours since you first visited.";
$('#timer').text(text);
}, 1000);
}
function hoursSinceFirstVisit() {
var currentDate = new Date();
var lastDate = new Date(JSON.parse(localStorage["mydate"]));
return hoursBetweenDates( lastDate, currentDate);
}
<div id="timer"></div>
Thanks!
There is no hoursBetweenDates function provided, so I added one. For debugging recursion errors, try moving the anonymous function to a named function as it is called repeatedly. Break code into smaller parts and make sure no part repeatedly calls itself:
$(document).ready(function() {
var myDate = new Date(2015, 4, 9, 0, 0);
localStorage.mydate = JSON.stringify(myDate);
function startTimer() {
setInterval(updateMessage, 100);
}
function updateMessage() {
var text = "It's been " + hoursSinceFirstVisit() + " hours since you first visited.";
$('#timer').text(text);
}
// This is my function for getting hours between dates
function hoursBetweenDates(d1, d2) {
return Math.abs(d1 - d2) / 36e5;
// For integer hours use this function
// return Math.floor(Math.abs(d1 - d2) / 36e5);
}
function hoursSinceFirstVisit() {
var currentDate = new Date();
var lastDate = new Date(JSON.parse(localStorage.mydate));
return hoursBetweenDates(lastDate, currentDate);
}
startTimer();
});
This will work fine without recursion errors. Here is a demo. Note, I made it return hours with decimal precision since the last visit, and set the interval to 100 ms to demonstrate it works fine. Update your version as you like. Apologies, I could not make a Stack Snippet because local storage is disabled.
Demo: http://jsbin.com/demevi/3/
The function setInterval() schedules a function to be executed repeatedly, waiting a specified number of milliseconds before each run.
If you want to delay the execution of function hoursSinceFirstVisit() (and run it only once) then you have to use setTimeout():
function startTimer() {
setTimeout(function() {
var text = "It's been " + hoursSinceFirstVisit() + " hours since you first visited.";
$('#timer').text(text);
}, 1000);
}

JavaScript Countdown Timer Code [JS]

I'm currently trying to get a countdown timer working but, I don't know JavaScript at all.
<script>
$(document).ready(function (e) {
var $timer = $("#timer");
function update() {
var myTime = $timer.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(0);
dt.setMinutes(ss[0]);
dt.setSeconds(ss[1]);
var dt2 = new Date(dt.valueOf() - 1000);
var temp = dt2.toTimeString().split(" ");
var ts = temp[0].split(":");
$timer.html(ts[1]+":"+ts[2]);
setTimeout(update, 1000);
}
setTimeout(update, 1000);
});
</script>
But I've stumbled upon a problem. So I want it to stop on 00:00, but it continues going.
Also at 2 minutes left and no time remaining I want it to execute some code.
At no time remaining (00:00) I want it to simply redirect to a page and at 2 minutes remaining I want it to run some custom code (Which I have).
But I have no idea on how to make it run at a time and make it stop at a time.
Can anyone help me with this?
Try
$timer.html(ts[1]+":"+ts[2]);
if((ts[1]==="02") &&(ts[2]==="00")){
//custom code at 02:00
}
if((ts[1]==="00") &&(ts[2]==="00")){
//Make the redirect
}
else{
setTimeout(update, 1000);
}
DEMO
The inner function should be a sybling of the anonymous function. Right now update(), can't be called because you are using setTimeout() -> update() should be on the same level as your anonymous function.

Detect when Date().getSeconds() has a new value

I want to detect a change in the value of Date().getSeconds() as soon as it happens.
I currently use:
function updateClock {
....
}
function detectChange(previousSec) {
var currentSec = new Date().getSeconds();
if (previousSec !== currentSec) {
updateClock();
}
}
setInterval(function () {
var dat = new Date();
var sec = dat.getSeconds;
detectChange(sec);
}, 10);
Is there a better way to do this?
Thanks!
How about a 2-step process?
First, align your clock with the system's 0-millisecond mark
setTimeout(startClock, 1000 - (new Date()).getMilliseconds());
Then, you only need to tick once per second
function startClock() {
setInterval(function do_your_thing() { ... }, 1000);
}
Practical demonstration (jsfiddle) shows that even if you do a large amount of work during the cycle, this method is pretty stable. In fact, on my machine you get better precision than the ±16ms resolution typically achievable in desktop task schedulers.
Unfortunately there is no standard event that fires when the clock changes seconds, so you'll need to set up an interval to detect it.
Setting an interval for every 1000ms means your clock could be off by almost a full second. Therefore I can understand why you'd want to check the seconds more than just once per second. The core concept here is sampling rate. The faster we sample the more precise we are, but the more processing time we waste detecting changes.
I think this will work for you.
function updateClock (date) {
console.log(date);
};
(function () {
var oldDate = new Date();
return setInterval(function () {
var date = new Date();
if (date.getSeconds() != oldDate.getSeconds()) {
updateClock(date);
}
oldDate = date;
}, 10); // precision is ~10ms
})();
It will have a new value after every one second, therefore just put a timer with 1 second interval.

Countdown end case resulting in Javascript error

I have a simple countdown plugin which counts down second by second to a time, and upon reaching that time it runs a callback function of my choosing.
What I have discovered today is that if I have two countdowns on the same page, and one countdown finishes, a javascript error occurs because a variable becomes undefined, which also breaks the second countdown.
Here's the code:
(function($) {
$.fn.countdown = function(options, callback) {
var $self = $(this);
var settings = {
'date' : null,
}
if(options) {
$.extend(settings, options);
}
function countdownProcessor() {
var eventDate = Date.parse(settings.date) / 1000;
var currentDate = Math.floor($.now() / 1000);
if (eventDate <= currentDate) {
callback.call(this);
clearInterval(interval);
}
var secondsBetween = eventDate - currentDate;
// processing logic here.
}
countdownProcessor();
interval = setInterval(countdownProcessor, 1000);
}
})(jQuery);
The issue is with the if statement which checks to make sure the date has not already occurred:
if (eventDate <= currentDate) {
callback.call(this);
clearInterval(interval);
}
When this condition becomes true, the callback completes successfully, but clearInterval does not because the variable interval is not defined - this is because the countdown function is run before interval is declared.
I've tried fixing it by switching the interval variable declaration and countdownProcessor(); around, but this doesn't help because it simply causes the first, ended countdown to count into the negatives.
I've a few other methods like changing the scope and order of declaration of some of the code, but it invariably leads to the countdown either A) counting into the negatives, or B) still erroring out.
How can I fix this?
Add var:
var interval = setInterval(countdownProcessor,1000);
This makes the interval local to each countdown that is being run, rather than global to the entire page.

How can I make a function execute after 2 minutes and then at 2 minute intervals after that?

I would like to call a function saveData($scope.data)
I understand there is an interval function in javascript but how can I make an initial interval of two minutes and then have that function repeatedly executed after that? I also need to save the new $scope.data each time
window.setTimeout(function(){
window.setInterval(function(){
saveData($scope.data);
},2*60*1000);
saveData($scope.data);
},2*60*1000);
online demo (with interval shorten to highlight effect)
The following function will execute saveData after every 2 minutes.
setInterval(function(){
saveData(data)
},
2*60*1000);
You can use
setTimeout("javascript function",milliseconds)
function for one time delay. Then use
setInterval("javascript function",milliseconds)
for specific time delay.
JS does not have a sleep function, you can implement your own function, like this
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
then call from your main function with your desire seconds

Categories