How to check time in JavaScript on load - javascript

I have a javascript function that runs an if-else statement depending on the time of day. Example:
window.setInterval(function(){
var date = new Date();
if(date.getHours() >= 15){
//code to run
} else {
//other code to run
}
}, 300000);
My problem is that it only refreshes to load what is in the if-else statement 300000 milliseconds(5 minutes) after the webpage is opened. However, I do not want to change that time to a very low digit and potentially cause issues from it refreshing so often. So the question is, can I make it check the time once on load, and then every 5 minutes after that?

Wrap your logic in a separate function. Call it on load and inside the interval.
window.addEventListener('DOMContentLoaded', (event) => {
const myIntervalFun = (date) => {
console.log(date.getHours())
if (date.getHours() >= 15) {
//code to run
} else {
//other code to run
}
}
myIntervalFun(new Date())
window.setInterval(function() {
myIntervalFun(new Date())
}, 3000);
});

Related

how to download data from axios in advance in vue?

In my app, I need to run my app offline because drivers have to use that app and in remote areas, they might not find internet for that purpose I need to download all data in advance through Axios request at the time they have internet. so that request can get data from the cache instead of server.
At the moment i tried this but this doesn't seems to be good practice
tryOffileWorkSheet: async function () {
Network.addListener("networkStatusChange", (status) => {
if (status.connected) {
setInterval(function () {
let worksheet = JSON.parse(localStorage.getItem("worksheet"));
if (worksheet == null) {
worksheet = [];
}
// localStorage.removeItem('worksheet')
for (let i = 0; i <= worksheet.length; i++) {
if(worksheet.length > 0){
setTimeout(function () {
if(worksheet[i]?.work_order_id){
ApiService.get(
`/api/gangBoss/work-sheet/${worksheet[i].work_order_id}/${worksheet[i].column_name}/${worksheet[i].value}`
).then((response) => {
if(response.data.status){
worksheet.splice(i,1)
localStorage.setItem("worksheet", JSON.stringify(worksheet));
}
console.log('After', worksheet)
// this.closeModal();
});
}
},i* 3000);
}
}
}, 3000);
}
});
},
also for this, it is necessary for the user to behave on this page when the internet available it means that we need to download a lot of data.
Can you please tell me the best practice to do that or plugin for vue which can help for that
The question is sort of unclear and is not maybe the best fit for SO, but I'll try to answer.
The first thing I noticed here is the use of setInterval, not that you are using it, but rather how. There's nothing that stops the interval from running. Here's a scenario that I hope illustrates the problem
networkStatusChange fired: status.connected === true
setInterval creates interval #1
3 seconds later interval #1 fires
... this keeps happening for the next 2 hours
networkStatusChange fired: status.connected === false
... interval#1 keeps firing
networkStatusChange fired: status.connected === true
setInterval creates interval #2
within 3 seconds interval #1 fires
3 seconds later interval #2 fires
... intervals #1 and #2 keep firing (twice within 3 seconds)
networkStatusChange fired: status.connected === false
networkStatusChange fired: status.connected === true
setInterval creates interval #3
within 3 seconds interval #1 fires
within 3 seconds interval #2 fires
3 seconds later interval #3 fires
... intervals #1, #2 and #3 keep firing (three within 3 seconds)
So there's two problems. The interval keeps firing regardless of whether the system is still connected.
You might be better of just firing every 3 seconds with a single timer, and exiting if the connection is not available. This also allows using window.navigator.onLine, which has much better browser support.
I don't know how long you expect worksheet to be, but if you have the ApiService called through setTimeout 3 seconds apart, and then call the parent function every 3 seconds, you're going to be sending a lot of requests.
tryOffileWorkSheet: function () {
// (need to create `intervalId` in data)
if (this.intervalId) clearInterval(this.intervalId);
this.intervalId = setInterval(() => {
if (window.navigator.onLine) {
this.getWorkSheet();
}
}, 3000);
},
getWorkSheet: function () {
let worksheet = JSON.parse(localStorage.getItem("worksheet"));
if (worksheet == null) {
worksheet = [];
}
for (let i = 0; i <= worksheet.length; i++) {
if (worksheet.length > 0) {
setTimeout(() => {
if (worksheet[i]?.work_order_id) {
ApiService.get(
`/api/gangBoss/work-sheet/${worksheet[i].work_order_id}/${worksheet[i].column_name}/${worksheet[i].value}`
).then((response) => {
if (response.data.status) {
worksheet.splice(i, 1);
localStorage.setItem("worksheet", JSON.stringify(worksheet));
}
console.log("After", worksheet);
});
}
}, i * 300);
}
}
},

Double interval call and it should not be in node.js

I have problem on server side (node.js) with setInterval.
I want to check something every day at specific time and I set interval like this:
let maintainTime = backFunc.getNextMaintainTime(new Date());
let maintain = setInterval(() => {
let currentTime = new Date();
if (currentTime.getTime() > maintainTime.getTime()) {
maintainTime = backFunc.getNextMaintainTime(maintainTime);
//do the maintain
}
}, 360000);
//360000 to check on every hour
and here is my getNextMaintainTime function:
getNextMaintainTime: (maintainTime) => {
maintainTime.setDate(maintainTime.getDate() + 1);
maintainTime.setHours(4);
maintainTime.setMinutes(0);
maintainTime.setSeconds(0);
maintainTime.setMilliseconds(0);
return maintainTime;
}
When I test it out it works perfectly but when I start server on production every time it calls this function 2 times instead of 1 time at 4am, what could cause the problem?

When I'm running my program I'm getting out of memory error

So, I actually wanna create a timer which will count back time, but when I'm running this script I'm always getting the 'Out of memory' error. Here is my onClick script:
handleClickStart = () => {
while (this.state.hours > 0) {
this.setState({
hours: this.state.hours - 1
})
}
}
Also I could show you the whole code if you'd need it
setState is asynchronous and it runs in batches, don't use setState inside a loop, rather create a new variable and set state at the end of the loop, like this
handleClickStart = () => {
let hours = this.state.hours;
while (hours > 0) {
hours --;
}
this.setState({hours});
}

Is there a way to fulfill a promise at an exact time?

I have a web page with transitions, On click everything goes to opacity:0 ( 1 second duration ) and then a new page is swapped in and everything goes to opacity:1 ( 1 second duration )
It ends up looking weird if the page doesn't have exactly 1 second to hide and appear. Also if the page doesn't get swapped immediately in between the two it looks award.
This was my first code
$('#main').css('opacity', '0');
setTimeout(function(){
$('#main').load('/views/'+name+'.html').css('opacity', '1')
}, 1000);
however load() sometimes takes too long to grab the view, and since the css is implemented immediately the opacity is already 1 when it swaps in.
so I tried this:
$.get('/views/'+name+'.html', function(page){
setTimout(function(){
$('#main').html(page).css('opacity', '1')
},1000);
})
But now if the $.get() is slow, the page is blank for too long.
Ideally I would like to know how long the promise took to fulfill, and subtract that from the setTimeout time.
I am thinking now that I have to manually create a new date object and check the difference after promise fulfillment.
Is there a better solution?
I forgot I can just use promises.
var pagePromise = $.get('/views/'+name+'.html')
$('main').css('opacity', '0')
setTimeout(function(){
pagePromise.then( function(page){
$('main').html(page).css('opacity', '1') }
)
},1000)
Just get time before and after your request. This may not be exact, but the error margin can easily be ignored for most purposes, yours included.
var time = Date.now();
$.get('/views/' + name + '.html', function(page) {
var elapsed = Date.now() - time;
setTimout(function() {
$('#main').html(page).css('opacity', '1')
}, 1000 - elapsed);
})
You can use Date.now() and calculate the difference.
var start = Date.now();
$.get('/views/' + name + '.html', function(page) {
setTimout(function() {
$('#main').html(page).css('opacity', 1);
}, 1000 - (Date.now() - start));
});
It's a little hard to tell exactly what you're trying to accomplish, but attempting to follow your logic, it appears that you want your new content to show up in one second after you hid the old content except when the content takes longer than that to load in which case, it shows up when it's loaded. You can do that by breaking the process down into a couple steps.
Record the starting time.
Fetch your content with ajax
When the content has been fetched, check how much time has elapsed.
If more than a second has elapsed, then just insert the content and show it.
If less than a second has elapsed, then set a timer for the remaining amount of time and then show the content when that timer fires.
You can implement that logic like this:
var begin = Date.now();
var main = $('#main').css('opacity', '0');
$.get('/views/'+name+'.html').then(function(content) {
main.html(content);
var elapsed = Date.now() - begin;
if (elapsed > 1000) {
// show it now
main.css('opacity', '1');
} else {
setTimeout(function(){
// show it when 1 second has finished
main.css('opacity', '1');
}, 1000 - elapsed);
}
});
Using this sort of notification and time measurement scheme, there is no guessing about load times.
You can use ajax and make your code synchronous.
jQuery.ajax({
url: '/views/'+name+'.html',
success: function (result) {
$('#main').html(page).css('opacity', '1');
},
async: false,
type: "GET"
});

JS variable containing ongoing time value

I'm working on a chatbot script (Hubot - running in terminal) exercise and looking for a method to count the time since the last message was left in the thread. Then after nobody has left a message for X number of minutes (let's say 10,000 milliseconds) I would like to console.log("CRICKETS!..CRICKETS!..")
I'm imagining something like:
//currentTime - startTime = timeSince
//and
// if( timeSince > 10,000)
// {console.log("Crickets!..")
however I'm not sure of how to create the currentTime variable as continuously growing counter
Below is the code I've started which doesn't appear to throw any errors in the , but also doesn't seem to work as I'm running it in the terminal. It just prints the current time twice
module.exports = function(robot) {
return robot.hear(/$/i, function(msg) {
var startTime = (Date.now()) ;
return(startTime);
if (Date.now() - startTime > 1000) {
console.log("CRICKETS..!...")
};
});
};
You'll notice I'm using Date.now() but I'm not attached if there's a better method. Also here is a link to basic hubot scripts in case it is needed for context - https://github.com/github/hubot/blob/master/docs/scripting.md
You can always use setTimeout and cancel it if need be
Pseudo-code:
var myTimeout = setTimeout(function () {
//nobody has left a message for 10 seconds
}, 10000);
if (user has left message)
clearTimeout(myTimeout);
The window.setTimeout function allows you to trigger a callback function after a delay. And you can clear that timeout by calling window.clearTimeout(value_returned_by_setTimeout).
We could define a callback: function crickets(){ console.log('Chirp! Chirp!'); }
Assuming some function newMessage gets called whenever a a new message appears, you could try something like this:
var cricketTimeout = null;
function newMessage(){
//... your code
if (cricketTimeout) clearTimeout(cricketTimeout);
cricketTimeout = setTimeout(crickets, delayInMilliseconds);
}

Categories