How to change setTimeout number? - javascript

lets say a website receives some data from users continuously. I want it to alert() users if it haven't received data from users in as long as 5 seconds.
this is How I'm trying to do it:
countDown = 5000
if(//some data received from user){
countDown = 5000
}
setTimeout(
function() {
alert('no data in 5 seconds')
}, countDown);
}
well it's not working because It can't set countDown to 5 sec every time It receives data from users, So How can I do this?
and since the data from user comes continuously I guess it wouldn't be good for performance to run a new setTimeout() and destroy the old one every time.(?)

This would be more of a recursive function that checks if there is any data. If not, it makes a function that runs in five seconds. If the data is still not there, you repeat the process.
let countDown = 5000
function someFunction() {
//this is called when you recieve data
timeoutFunc();
}
function timeoutFunc() {
setTimeout(
function() {
if (//still don't have new data) {
alert('no data in 5 seconds');
timeoutFunc();
}
}, countDown);
}
}

Related

Is there any way to get milliseconds in CronJobs?

I want to render JavaScript function in every 500ms using node Cronjobs.
But I could find function for every 1 second as below.
cron.schedule("*/1 * * * * *", function() {
console.log("running a task every 1 second");
});
Is there anyway to run function on every 500ms using node Cronjob?
Setting a cron job to execute that frequently is not possible, and for good reason - a task executing that frequently shouldn't be done using a cron.
Instead, you can use Timers with Node.js:
function myFunc(arg) {
console.log("Argument received: " + arg);
}
setTimeout(myFunc, 500, "some message"); // Executes every 500ms.
Timers can also be instantiated into a variable:
const timeoutObject = setTimeout(() => {
console.log("I will print every 500ms!");
}, 500);
clearTimeout(timeoutObject);

How to fetch data (method call) every five seconds in Flutter?

In JavaScript, I could constantly fetch data without an explicit request from the user by calling a function fetchData() every five seconds using setInterval(function() { fetchData() }, 5000); and this is an incredibly useful tool for me. Is there a similar equivalent in Flutter?
This can be achieved by something like this.
import 'dart:async';
main() {
const fiveSeconds = const Duration(seconds: 5);
// _fetchData() is your function to fetch data
Timer.periodic(fiveSeconds, (Timer t) => _fetchData());
}
Timer() and Timer.periodic() work the same way. They take duration as a parameter and an optional callback function.
Timer(const Duration(seconds: 5), () {
// these lines would be executed every 5s.
});

How to run a javascript function multiple time till you satisfy the if condition

I have an Ajax call which I want run multiple times till it satisfies a particular if condition. The AJAX call gives you the job status-Running, Queued and Complete.
I am unable to get the Job status- Complete. After getting Running status it takes a couple of minutes to get the status Complete. So far I have tried the following JS. I also want to break the loop after the if condition has been met. I am also not sure if I should run the call for 100 times as it might take more than that. Thank you for your help.
My JS:
var pollForJob= gallery.getJob(jobId, function(job){
var jobStat=job.status;
console.log(jobStat);
if(jobStat=="Complete"){
alert("Complete");
} else {
// Attempt it again in one second
setTimeout(pollForJob, 1000);
console.log("still working");
console.log(jobStat);
}
}, function(response){
var error = response.responseJSON && response.responseJSON.message ||
response.statusText;
alert(error);
// Attempt it again in one second
setTimeout(pollForJob, 1000);
});
Like Jeremy Thille said, this is called long polling. A simple way of doing it is to create a function which makes the call out to the server. Then, if it fails, use setTimeout to queue up another request later.
function pollForJob() {
gallery.getJob(jobId, function(job) {
var jobStat = job.status;
if (jobStat == "Complete") {
alert("Complete");
} else {
// Attempt it again in one second
setTimeout(pollForJob, 1000);
}
}, function(response) {
var error = response.responseJSON && response.responseJSON.message || response.statusText;
console.error(error);
// Attempt it again in one second
setTimeout(pollForJob, 1000);
});
}
pollForJob();

Sleep() not working as expected

In my code, I'm trying to put a certain delay before continuing to the rest of the code. Pretty basic. I'm using a custom sleep function because javascript's native sleep function is not working at all. I'm actually working in app script in google spreadsheets so maybe that's why. But the following code is in the <script> tag of the html file in spreadsheet app script.
Anyway, when I use sleep(), it is being executed before the setTimeout
function get_ids(db){
window.alert("before window.ids is saved?");
google.script.run.withSuccessHandler(getIdsFromAppscript).getIdsFromModel(db);
//this returns a result to getIdsFromAppscript but the following code doesn't wait
//for the result to be returned so I want to use sleep before the ids
//variable is returned by get_ids
setTimeout(function(){
window.alert("checking if ids is saved after 10s?");
window.alert("In timeout ids="+window.ids);
var ids= window.ids; //is non empty
},10000);
sleep(10000);
var ids= window.ids;
window.alert("after wait");
window.alert("after sleep ids="+ids); //is empty but should be non empty
return ids; //=window.ids , Need to return a non-empty result
}
function getIdsFromAppscript(result){
window.ids=result;
}
and the sleep function:
function sleep(ms) {
var start = new Date().getTime(), expire = start + ms;
while (new Date().getTime() < expire) { }
return;
}
Current Order of output based on window.alert():
1) before window is saved?
2) after sleep
3) after sleep ids= //basically empty which shouldn't be the case
4) checking if ids is saved after 10s?
5) In timeout ids= [.....] //non empty list
However, my desired output order is:
1) before window is saved?
2) checking if ids is saved after 10s?
3) In timeout ids= [.....] //non empty list
4) after sleep
5) after sleep ids= [...] //should be a non empty list
The reason why I'm writing setTimeout is to show that after 10 seconds, the result is being stored in window.ids however even after I give a sleep for 10 seconds, or even 30 seconds, I can't get the result from window.ids.
What exactly am I doing wrong here? Thanks in advance~
Java Script, especially through the V8 engine does not sleep. Sleeping causes the entire thread that JavaScript runs on to stop, which breaks the whole point of asynchronocy. setTimeout() only waits to run the function you push into it for the time you also put into it. It doesn't stop the rest of the executions, and whatever happens first will happen first.
If it's important to you that something happens in order, always, then you need to use callbacks or promises.
An example in code could be:
function doTimeout(ms) {
setTimeout(function(){
window.alert("checking if ids is saved after 10s?");
window.alert("In timeout ids="+window.ids);
var ids= window.ids; //is non empty
},ms);
}
function sleep(ms, callback) {
var start = new Date().getTime(), expire = start + ms;
while (new Date().getTime() < expire) { }
callback(ms);
}
sleep(10000, doTimeout);
Javascript is single threaded. You must return from your code for scripts in other threads to execute. Script in other threads includes functions to handle a timeout event, functions called when promises are kept or fail, and call back functions provided for asynchronous requests made using an XMLHttpRequest object.
Writing a function and calling it sleep() does not change this. You could have called it waitingForGodot() for all the difference it would make. What the code you provided does is to spend a lot of time looping in the thread it was called in. It does not relinquish control and blocks all other scripts from executing. If it goes on for long enough my browser will ask me if I wish to abort the (as in your) script.
I have included two examples below showing that your sleep function blocks the entire Javascript engine. When I use your sleep function, the interval function does not get executed even though I have set an interval of 100 ms and the output is delayed by 10 seconds. However, in the second example the output does get printed immediately at the correct interval. This shows your sleep function is blocking the entire execution engine and that explains why your ids array is empty.
function sleep(ms) {
var start = new Date().getTime(),
expire = start + ms;
while (new Date().getTime() < expire) {}
return;
}
function get_ids() {
document.write("before window.ids is saved?" + "<br>");
var counter = 0;
setInterval(function() {
while (counter < 100) {
document.write("checking if ids is saved after 10s?" + "<br>");
counter = counter + 1
}
}, 100);
sleep(10000);
documen.write("after wait");
}
document.write("Start");
get_ids()
document.write("End");
In this example I have commented out your sleep function and as expected the output gets printed every 100 ms:
function sleep(ms) {
var start = new Date().getTime(),
expire = start + ms;
while (new Date().getTime() < expire) {}
return;
}
function get_ids() {
document.write("before window.ids is saved?" + "<br>");
var counter = 0;
setInterval(function() {
while (counter < 100) {
document.write("checking if ids is saved after 10s?" + "<br>");
counter = counter + 1
}
}, 100);
//sleep(10000);
documen.write("after wait");
}
document.write("Start");
get_ids()
document.write("End");

Chat application polling

I'm working on a chat application, which polls the server at a timeout.
The timeout increases if, over time, there hasn't been any recent activity.
The function loadNew() performs an ajax call to the server, which responds with message data.
pollTimeoutTime = 500;
function poll() {
pollTimeout = setTimeout(function(){
loadNew();
if (!new_messages_count) {
//Increasing delay between polls as no messages are incoming to a maximum of 1 minute/60 seconds
if (pollTimeoutTime < 60000) pollTimeoutTime = pollTimeoutTime * 1.25;
}
else {
//Reset delay between poll to default of 0.5 seconds
pollTimeoutTime = 500;
}
poll();
},pollTimeoutTime);
}
The problem I'm having is that the timeout function does not wait for the function loadNew() to complete, which causes the same poll to be sent twice or more if the timeout is lower than the time it takes for the ajax call in the function to complete.
The server thus responds with the same data multiple times, which leads to duplicative display of messages in the chat.
Is there a way to make the timeout only trigger after loadNew() has finished fetching and displaying the data?
EDIT: after using #Brad M's answer, it doesn't duplicate messages anymore. I would still like to have a way to call for a poll after the user submits a message, so the new message is displayed immediately. This would interfere with the timeout set in loadNew(), which would cause messages to be duplicated again. Could you think of a way to get that working?
Without seeing your loadNew function, an easy fix might be to change that function to return your ajax call (return $.ajax({...});) and change the code you posted to this:
pollTimeoutTime = 500;
function poll() {
pollTimeout = setTimeout(function () {
loadNew().done(function (result) {
if (!new_messages_count) {
//Increasing delay between polls as no messages are incoming to a maximum of 1 minute/60 seconds
if (pollTimeoutTime < 60000) pollTimeoutTime = pollTimeoutTime * 1.25;
} else {
//Reset delay between poll to default of 0.5 seconds
pollTimeoutTime = 500;
}
poll();
});
}, pollTimeoutTime);
}
Use ajax callback functions such as success or complete to trigger a new poll.

Categories