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 11 days ago.
Improve this question
I'm new with RXJS and I would like to do a function which checks recursively a status until it will be "Available". I found this with vanilla JS to represent what I'm looking for:
setTimeout(() => {
this.updateStatus();
},status === 'Pending' ? 0 : 2000);
You've mentioned you want to keep checking the status until it's available. I'm assuming you're looking for some kind of polling, but your code snippet with the the setTimeout() method will only run once after a delay and won't keep calling the updateStatus method. If you wanted to do a vanilla JS timer you'd need to look at using setInterval()
If you want to check every few seconds using rxjs, one solution could be to use the timer. The timer will emit an event every period milliseconds, after an initial delay of delay milliseconds. See here for docs
You could do something along these lines:
timer(delay, interval)
.pipe(
tap(() => this.updateStatus())
filter(() => this.status === 'Available'),
take(1)
).subscribe(() => {
console.log('Complete');
//do work here
});
This example uses the tap operator to call your updateStatus method every interval milliseconds after the initial delay has passed. Once your status var is set to 'Available', the observable will fire and the code in the subscribe block will be executed. The take(1) ensures that only one emission gets through once the status is no longer pending, so your observable will be closed and the timer will no longer have any active subscribers.
If your intent is to only check once, you can also use the timer to run once after a delay, similar to your setTimeout() example:
timer(delay).subscribe(x => {
this.updateStatus();
//do something here.
})
Related
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
I have some socket.io emits that I'd like to provide handling for when they are taking too long to get back from the server with their promise. But I also don't want to outright time them out. I have seen this on some websites where a loading spinner will add 'This seems to be taking longer than usual' text after 10 or so seconds.
How can I add a timeout-style method to a Javascript function that will do something after a certain amount of time, but will NOT cancel the original method?
Unless you have a global scope, you'll need to pass in two handlers
Something like this (I've generalised the flow because you've not provided enough information about your existing set up, so I hope it makes sense)
function doSocketRequest(normalHandler, tooLongHandler) {
let timer = null;
// set timeout to 5 seconds, if we hit it then trigger "tooLongHandler"
timer = setTimeout(tooLongHandler, 5000);
// When we receive our socket response for the event, clear the time and trigger "normalHandler"
socket.on('some_event_response', (response) => {
clearTimeout(timer);
normalHandler(response)
});
// Emit to server
socket.emit('some_event', ...etcetc);
}
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 2 years ago.
Improve this question
I am currently working on a game in which a timer will be needed, but the one made in js has a very long delay and on each device it is different, which in the case of a ranking where milliseconds count is unacceptable.
I want to create a stopwatch that will be synchronized with the server time and will have the smallest local delay and will show the elapsed time with an accuracy of 0.01 seconds. Any idea how i can do this?
My code look like this:
var stopper = setInterval(myTimer, 10);
let time = 0;
let run = true;
function myTimer() {
if(run) {
time += 0.01;
//update time display
}
}
You can keep something startTime on the server and use on the client to calculate passed time.
If you need to keep the time and update necessarily then try to use websocket
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 7 years ago.
Improve this question
I don't know how to make a Javascript count up that is related to the real time, which means when you reload the page, the counter won't start over again. Would anybody tell me how to make that happen :) Example like http://www.worldometers.info/ Thanks a lot.
The code they are using is likely pulling from a database with an actual value increasing live.
Check out this js fiddle I made for an example of how a simple timer can work. Notice that if you press "Run" multiple times, the time itself will stay constant.
Using a remote database will cause a lot more work, but for saving values across browser refreshes you should learn about localStorage I'd check out W3 School's article on the subject.
In my implementation I use
localStorage.setItem("time", currentTime); // Note that CurrentTime must be a string!
in each iteration of your code after setting the currentTime var.
When you start up your application, a simple if statement
if (localStorage.getItem("time") {
CurrentTime = localStorage.getItem("time");
} else {
// set default values
}
will work, as localStorage.getItem will return null if the value doesn't exist (or if you set the value to null manually).
(for localStorage, you can also use [bracket notation] and will probably see that in most common examples)
localStorage["foo"] = "value";
// is the same as:
localStorage.setItem("foo", "value")
// and
var bar = localStorage["foo"];
// is the same as:
var bar = localStorage.getItem("foo");
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 7 years ago.
Improve this question
When I'm trying use function like sleep(2) in a new function I wrote, it's not working.
function deleterow(id){
$.post( "taskpost.php", { "deleteid": id, "delete":true } );
sleep(1);
$('#taskslist').load('taskslist.php').fadeIn('slow');
};
Have you coded sleep function or are you using it from some other library?
If you want to wait for the post request to complete try using this:
$.post("taskpost.php", { "deleteid": id, "delete":true } )
.done(function(data){
$('#taskslist').load('taskslist.php').fadeIn('slow');
});
If you still want to delay it somewhat you can use setTimeout inside done callback.
There is no such function as sleep() in Javascript. If you are attempting to add a delay to your function, use setTimeout(callback,delay) instead.
I think I know what the problem is. Maybe the post in jQuery isn't working. Sometimes when you have a function that can't be found/finished, it stops the previous function from continuing. The other problem is that there is no sleep function. If you are trying to delay, use the setInterval function.
Good luck!
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to activate an audio file every round 15 minutes using Date Object.
I have tried to use a while loop to determine the specific time but it's not working.
Check out setInterval()
Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
and setTimeout().
Calls a function or executes a code snippet after a specified delay.
I'd imagine you'll use these in conjunction with an <audio> element for playback.
A quick solution would be something like this (fiddle):
(function () {
var time = new Date().getTime();
var interval = 900000;
function playAudio() {
document.getElementById('audio-test').play();
}
setTimeout(function () {
playAudio();
setInterval(playAudio, interval); // execute on interval
}, interval - time % interval); // execute at next interval
})();
Perform a setTimeout to catch up to the next interval and then use setInterval after that. One caveat to this approach is that the delay specified for these functions is a minimum delay, i.e.: the actual delay may be longer. So, the interval could drift out of accuracy.
Alternatively, you could poll at a shorter interval and check that the minutes are evenly divided by 15. Here's a fiddle
(function () {
var last;
setInterval(function(){
var minutes = new Date().getMinutes();
if(minutes % 15 === 0 && last !== minutes){
last = minutes;
document.getElementById('audio-test').play();
}
},1000);
})();