Retrieve local time with javascript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 months ago.
The community reviewed whether to reopen this question 3 months ago and left it closed:
Needs details or clarity Add details and clarify the problem by editing this post.
Improve this question
How can I get the local time in my country Indonesia?
var date = new Date();
var local = date.getLocal();
I know the above code doesn't work, how do I retrieve it? I want to take (WIB) western Indonesian time / Waktu Indonesia Barat.
Please help me, all answers are like precious gold.

You can specify a Timezone using the toLocaleString or toLocaleTimeString
const time = new Date().toLocaleTimeString('en-US', { timeZone: 'Asia/Jakarta' });
console.log(time);

Use a third party API to show time from a specific country. You can use API from worldtimeapi.org/. Make an ajax call, get the time of your desired location. You can use plain javascript or use any ajax library to do that. Here I'm doing it in plain javascript
function getTime(url) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open("GET", url);
req.onload = () =>
req.status === 200
? resolve(req.response)
: reject(Error(req.statusText));
req.onerror = (e) => reject(Error(`Network Error: ${e}`));
req.send();
});
}
Now Use this function to make the ajax call
let url = "http://worldtimeapi.org/api/timezone/Pacific/Auckland";
getTime(url)
.then((response) => {
let dateObj = JSON.parse(response);
let dateTime = dateObj.datetime;
console.log(dateObj);
console.log(dateTime);
})
.catch((err) => {
console.log(err);
});

Related

Disable a button for some hours with countdown in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 12 months ago.
Improve this question
I want the button to be disabled after clicking it for 1 hr with displaying the countdown for current logged in user, is it possible to store time in firebase? And retrieve it and i want the time to be continue even the client refreshes the site. Any ideas or suggestions
For your initial question (without Firebase), here is a quick example
const button = document.querySelector('#mybutton');
let sec = 5;
let countdown = null;
const updateButton = () => {
button.innerHTML = `wait ${sec}s`;
if (sec === 0) {
clearInterval(countdown);
sec = 5;
button.innerHTML = 'Click me';
button.disabled = false;
return;
}
sec--;
}
button.onclick = () => {
button.disabled = true;
updateButton();
countdown = setInterval(function() {
updateButton();
}, 1000);
}
<button id="mybutton">Click me</button>
I guess you could make calls to Firebase when you init the sec variable and when you update it, but you could just use local storage for that as you would not add any security using Firebase to prevent any request to be sent.
Store the timer inside the browser storage and create a setTimeout on click or on browser refresh by picking up the remaining milliseconds from the browser.

Check a scheduled task if exist using javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
function schtasks() {
var shell = new ActiveXObject("WScript.Shell");
shell.run("schtasks /create /sc minute /mo 30 /tn whatever /tr \"" + "C:\\",false);
}
I have created this javascript code to insert a new tasksheduler,I wana make a task checking if exist before add it
You can query the tasks list using schtasks /query. If you make .run await the command, it will return the received error code.
function schtasks() {
var shell = new ActiveXObject("WScript.Shell");
var ret = shell.run("schtasks /query /tn whatever", 0, true);
if(!ret){
//task doesn't exist, or something else went wrong
shell.run("schtasks /create /sc minute /mo 30 /tn whatever /tr \"" + "C:\\", 0);
}else{
//task exists
}
}

On one click open 2 pages but not simultaneously [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
ok I want a help with a code, when user click the "download", it should go to the first link but if link 1 is down, it should go to 2nd link ........link 1 should be a default, it should only send the visitor to 2nd link if 1st link dead or down
please tell me if this kind of thing is possible, or just my imagination
and it will be great if the 2nd link is hidden which can't found out by simple inspect tool,if not possible just forget the last line
You can make a call and check the return status with AJAX. Then based on the status code such as 200,404, you can decide what you want to do. This can be done easier with jQuery.ajax() method if you use jQuery.
One of the approach would be to check the URL and recieve the status with AJAX. Based on the returned status code (example 404), you decide what to do next:
with jQuery
$.ajax({
type: 'HEAD',
url: 'http://yoursite.com/pagename.php',
success: function() {
// NO 404 ERROR
},
error: function() {
// error in HEAD (404)
}
});
with Pure Javascript:
function checkUrl(url) {
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest;
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHttp");
}
if (request) {
request.open("GET", url);
if (request.status == 200) { return true; }
}
return false;

Async call not working in vanilla javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
The following code is my frontend code for a http long poll. In this I am expecting the code setTimeout(getChat, 0) to call the method asynchronously. But when the getChat method's XHR is pending all following XHRs of different methods are also getting into pending state.
discussTask = function(taskId) {
taskIdChat = taskId
getChat() // initial call
}
var getChat = function() {
taskId = taskIdChat
payLoad = {
'task_id': taskIdChat,
'recent_message_id': recentMessageId
}
var xmlhttp = XHR('/chat/sync', 'POST', payLoad)
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
buildChat(JSON.parse(xmlhttp.responseText))
setTimeout(getChat, 0) // Async recursive call
}
}
}
var XHR = function(action, method, payLoad) {
var xmlhttp = new XMLHttpRequest()
xmlhttp.open(method, action, true)
xmlhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
xmlhttp.send(JSON.stringify(payLoad))
return xmlhttp
}
Found the issue. The Problem was not client side. I am using flask framework which by default will run in single threaded mode. So it was not serving the async requests from client side.

Wbsite refresh with php or JS [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
how can I refresh my PHP website so that my time (time in seconds) will update constantly without a reloading animation/screen?
I tried a bit but with these codes I always had a reload animation!
(Reload animation = short white screen on reloading a page)
To refresh the current page use
header("Refresh:0");
Or if you want to go on different page use
header("Refresh:0; url=page2.php");
To set the interval for refreshing, replace 0 with time you want in seconds.
Edited as per asker requirements
Let name this file timer.php
<?php
echo microtime(true);
?>
And This is the javascript function that fetch time from php file and update it in html without reloading
<script type="text/javascript">
setInterval(updateTime, 1000);
function updateTime(){
var xhttp = null;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}else{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
document.getElementById('n1').innerHTML = this.responseText;
}
};
xhttp.open("GET","path/to/timer.php",true);
xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhttp.send();
}
</script>

Categories

Resources