async and set timeout - javascript

I am having some problem using the settimeout() in my function. I am new to async. No matter how much I try I just can't make the timeout work. My code works perfect so that is not the problem. I need the request to execute every 10 seconds. Thanks for the help.
function getContent() {
function getPelicula(pelicula, donePelicula) {
var peli = pelicula.title;
//request id
request({
url: "http://api.themoviedb.org/3/search/movie?query=" + peli + "&api_key=3e2709c4c051b07326f1080b90e283b4&language=en=ES&page=1&include_adult=false",
method: "GET",
json: true,
}, function(error, res, body) {
if (error) {
console.error('Error getPelicula: ', error);
return;
}
var control = body.results.length;
if (control > 0) {
var year_base = pelicula.launch_year;
var id = body.results[0].id;
var year = body.results[0].release_date;
var d = new Date(year);
var year_solo = d.getFullYear();
if (year_base == year_solo) {
pelicula.id = id;
pelicula.year_pagina = year_solo;
}
} else {
pelicula.id = null;
pelicula.year_pagina = null;
}
donePelicula();
});
}
}

To do something in a loop, use setInterval.
UPD:
In general, there're two ways of executing some code in loop
1 setTimeout :
var someTimer = setTimeout(function sayHello(){
console.log("hello!");
someTimer = setTimeout(sayHello, 2000);
}, 2000);
Notice that someTimer variable is needed to stop the looping process if you need: clearTimeout(someTimer)
2 setInterval:
var someIntervalTimer = setInterval(function(){
console.log("I'm triggered by setInterval function!");
}, 2000);
Invoke clearInterval(someIntervalTimer) to stop the looping
Both functions are treated as properties of the global Window variable. By default, the following code works:
var window = this;
console.log("type of setTimeout: " + typeof window.setTimeout);
console.log("type of setInterval: " + typeof window.setInterval);

Try putting it in another function so:
domore(pelicula,donePelicula);
function domore(pelicula,donePelicula) {
// 1 second
var timeout = 1000;
for (var i = 1; i < pelicula.length; i++) {
createData(pelicula[i],donePelicula,timeout);
timeout = timeout + 800;
}
}
function createData(peli,donePelicula,timeout) {
setTimeout(function() { getData(peli,donePelicula); }, timeout);
}
function getData(peli,donePelicula) {
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://api.themoviedb.org/3/search/movie?query=" + peli + "&api_key=3e2709c4c051b07326f1080b90e283b4&language=en=ES&page=1&include_adult=false", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
domore(allText,donePelicula);
}
}
}
txtFile.send(null);
}

Related

Stopwatch frontend app stop, when tab is not active [duplicate]

So basically when I switch tabs, the countdown timer on a specific page just stops counting down and resumes when you return to the tab. Is there anyway to mitigate that so that it counts in the background or it accounts for the time you spend on another tab?
This is basically what I have for js:
document.getElementById('timer').innerHTML =
05 + ":" + 01;
startTimer();
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
if(m<0){
return
} else if (m == 0 && s == 0) {
location.reload();
}
document.getElementById('timer').innerHTML =
m + ":" + s;
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec};
if (sec < 0) {sec = "59"};
return sec;
}
Any ideas whether the time could be done server side or something so that it can't be modified client side? If not, then whatever, but mainly just want to figure out how to make the countdown still work (or account for the time spent) when on another tab.
We can store the variable m and s values either globally or use the local storage to set the values after setting the inner HTML and get the stored values back whenever tabs were switched as:
Set values:
window.localStorage.setItem('minutes', m.toString()); //same for the seconds
Get values:
window.localStorage.getItem('minutes'); //same for the seconds
Hope this answers your questions.
Just a simple solution:
Add this piece of code.
<html>
<head>
<script>
(function() {
var $momentum;
function createWorker() {
var containerFunction = function() {
var idMap = {};
self.onmessage = function(e) {
if (e.data.type === 'setInterval') {
idMap[e.data.id] = setInterval(function() {
self.postMessage({
type: 'fire',
id: e.data.id
});
}, e.data.delay);
} else if (e.data.type === 'clearInterval') {
clearInterval(idMap[e.data.id]);
delete idMap[e.data.id];
} else if (e.data.type === 'setTimeout') {
idMap[e.data.id] = setTimeout(function() {
self.postMessage({
type: 'fire',
id: e.data.id
});
// remove reference to this timeout after is finished
delete idMap[e.data.id];
}, e.data.delay);
} else if (e.data.type === 'clearCallback') {
clearTimeout(idMap[e.data.id]);
delete idMap[e.data.id];
}
};
};
return new Worker(URL.createObjectURL(new Blob([
'(',
containerFunction.toString(),
')();'
], {
type: 'application/javascript'
})));
}
$momentum = {
worker: createWorker(),
idToCallback: {},
currentId: 0
};
function generateId() {
return $momentum.currentId++;
}
function patchedSetInterval(callback, delay) {
var intervalId = generateId();
$momentum.idToCallback[intervalId] = callback;
$momentum.worker.postMessage({
type: 'setInterval',
delay: delay,
id: intervalId
});
return intervalId;
}
function patchedClearInterval(intervalId) {
$momentum.worker.postMessage({
type: 'clearInterval',
id: intervalId
});
delete $momentum.idToCallback[intervalId];
}
function patchedSetTimeout(callback, delay) {
var intervalId = generateId();
$momentum.idToCallback[intervalId] = function() {
callback();
delete $momentum.idToCallback[intervalId];
};
$momentum.worker.postMessage({
type: 'setTimeout',
delay: delay,
id: intervalId
});
return intervalId;
}
function patchedClearTimeout(intervalId) {
$momentum.worker.postMessage({
type: 'clearInterval',
id: intervalId
});
delete $momentum.idToCallback[intervalId];
}
$momentum.worker.onmessage = function(e) {
if (e.data.type === 'fire') {
$momentum.idToCallback[e.data.id]();
}
};
window.$momentum = $momentum;
window.setInterval = patchedSetInterval;
window.clearInterval = patchedClearInterval;
window.setTimeout = patchedSetTimeout;
window.clearTimeout = patchedClearTimeout;
})();
</script>
</head>
</html>

How to delay a JavaScript JSON stream for one minute?

I am ask to write a java script program that retrieve an api JSON record from and address and through websocket every single minute. The stream continues after 60 seconds. I am expected to return the respective stream retrieve and the stream from the previous retrieve . Below is my code
var obj=
{
seconds : 60,
priv : 0,
prevTick : '' ,
data : ''
}
function countTime()
{
obj.seconds --;
obj.priv ++;
var msg ;
if(obj.priv > 1)
{
obj.priv = 0;
obj.msg = null;
}
if(prop.seconds < 0)
{
msg = sock.open();
obj.msg = obj.msg + ", New Tick : " + msg.msg ;
setTimeout(countTime, 1000);
obj.seconds = 60;
}
}
var sock= new WebSocket('link');
sock.onopen = function(evt) {
ws.send(JSON.stringify({ticks:'string'}));
};
sock.onmessage = function(msg) {
var data = JSON.parse(msg.data);
return 'record update: %o'+ data ;
};
Please what is wrong with my code above ? It does not delay at all. The stream continues irrespective.
How about encapsulating the buffering behavior into a class?
function SocketBuffer(socket, delay, ontick) {
var messages = [], tickInterval;
socket.onmessage = function(msg) {
messages.push( JSON.parse(msg.data) );
};
function tick() {
if (typeof ontick !== "function") return;
ontick( messages.splice(0) );
}
this.pause = function () {
tickInterval = clearInterval(tickInterval);
};
this.run = function () {
if (tickInterval) return;
tickInterval = setInterval(tick, delay * 1000);
tick();
};
this.run();
}
Note that .splice(0) returns all elements from the array and empties the array in the same step.
Usage:
var link = new WebSocket('link');
link.onopen = function (evt) {
this.send( JSON.stringify({ticks:'string'}) );
};
var linkBuf = new SocketBuffer(link, 60, function (newMessages) {
console.log(newMessages);
});
// if needed, you can:
linkBuf.pause();
linkBuf.run();
Try this:
function countTime() {
var interval = 1000; // How long do you have to wait for next round
// setInterval will create infinite loop if it is not asked to terminate with clearInterval
var looper = setInterval(function () {
// Your code here
// Terminate the loop if required
clearInterval(looper);
}, interval);
}
If you use setTimeout() you don't need to count the seconds manually. Furthermore, if you need to perform the task periodically, you'd better use setInterval() as #RyanB said. setTimeout() is useful for tasks that need to be performed only once. You're also using prop.seconds but prop doesn't seem to be defined. Finally, you need to call countTime() somewhere or it will never be executed.
This might work better:
var obj=
{
seconds : 60,
priv : 0,
prevTick : '' ,
data : ''
}
function countTime()
{
obj.seconds --;
obj.priv ++; //I don't understand this, it will always be set to zero 3 lines below
var msg ;
if(obj.priv > 1)
{
obj.priv = 0;
obj.msg = null;
}
msg = sock.open();
obj.msg = obj.msg + ", New Tick : " + msg.msg;
obj.seconds = 60;
//Maybe you should do sock.close() here
}
var sock= new WebSocket('link');
sock.onopen = function(evt) {
ws.send(JSON.stringify({ticks:'string'}));
};
sock.onmessage = function(msg) {
var data = JSON.parse(msg.data);
return 'record update: %o'+ data ;
};
var interval = setInterval(countTime, 1000);
EDIT: finally, when you're done, just do
clearInterval(interval);
to stop the execution.

setTimeout and setInterval

I want to make this counter starts working within 5 seconds of being on the page, but I can not link the setTimeout with setInterval , you would know how could I?
Try to wrap your interval with the setTimeout function:
// interval variable
var cycle = 10;
// variable for the interval since we are invoking it within a function, the callMeEverySecond function can't reach it
var t;
var callMeEverySecond = function() {
cycle--;
// Logs the Date to the console
console.log(new Date());
if(cycle === 0) {
console.log("stop this");
clearInterval(t);
// do something further.
}
}
// Start the timeout after 5 seconds
setTimeout(function() {
// call the function 'callMeEverySecond' each second
t = setInterval(callMeEverySecond, 1000);
}, 5000);
http://devdocs.io/dom/window.settimeout
And a small tutorial: http://javascript.info/tutorial/settimeout-setinterval
Is this ok
var tiempoInicial = 10;
function tiempo() {
document.getElementById('contador').innerHTML='Puedes continuar en ' + tiempoInicial + ' segundos.';
if(tiempoInicial==0) {
clearInterval(t);
document.getElementById("contador").innerHTML = "<p id=\"forumulario\" onclick=\"goToForm1()\">Continuar</p>";
}
}
function iniciar() {
var t = setInterval(tiempo,1000);
clearTimeout(ini);
}
var ini = setTimeout(iniciar, 5000);
Sorry, I tried out the code above and it didn't work so I changed it a bit.
This is the new code.
var tiempoInicial = 10;
function tiempo() {
document.getElementById('contador').innerHTML='Puedes continuar en ' + tiempoInicial + ' segundos.';
tiempoInicial--;
if(tiempoInicial < -1) {
clearInterval(t);
document.getElementById("contador").innerHTML = "<p id=\"forumulario\" onclick=\'goToForm1()\'>Continuar</p>";
}
}
function iniciar() {
t = setInterval(tiempo,1000);
clearTimeout(ini);
}
var ini = setTimeout(iniciar, 5000);

Break a for loop from within an anonymous function

I'm trying to break a for-loop (labeled) from within a nested anonymous function, like this:
function ajax(iteration, callback) {
var rtrn, xh;
if (window.XMLHttpRequest) {
xh = new XMLHttpRequest();
} else {
xh = new ActiveXObject("Microsoft.XMLHTTP");
};
xh.onreadystatechange = function() {
if (xh.readyState == 4 && xh.status == 200) {
callback(xh.responseText);
};
};
xh.open("GET", "file.php?i=" + iteration, true);
xh.send();
};
var atk_delay = 100;
loop:
for(i = 1; i <= 40; i++) {
var to = atk_delay * i;
setTimeout(
function() {
ajax(i, function(responseText) {
var div = document.getElementById("combat");
div.innerHTML += responseText;
var arrRt = responseText.split("::");
if(arrRt[0] == "stop") {
break loop;
};
});
},
to);
};
I really have no idea how to solve this. Obviously, the problem is that it cannot find the label. How can I resolve this?
So I solved it! Thanks for the help guys! You got me to realize I needed a completely different approach!
function ajax(callback) {
var rtrn, xh;
if (window.XMLHttpRequest) {
xh = new XMLHttpRequest();
} else {
xh = new ActiveXObject("Microsoft.XMLHTTP");
};
xh.onreadystatechange = function() {
if (xh.readyState == 4 && xh.status == 200) {
callback(xh.responseText);
};
};
xh.open("GET", "file.php", true);
xh.send();
};
var atk_delay = 100;
function roll() {
ajax(function(responseText) {
var div = document.getElementById("combat");
div.innerHTML += responseText;
var arrRt = responseText.split("::");
if(arrRt[0] == "cont") {
setTimeout(roll, atk_delay);
};
});
};
setTimeout(roll, atk_delay);
Normally what you would do is have a variable that's accessible after each iteration of the loop that would indicate if you can break. This would be set in the anonymous function.
However, in your specific case, since you are calling setTimeout, execution of the loop might have been completed by the time you can even set the value. setTimeout schedules the function to later execution (in ms).
You can use a variable to exit the anonymous function early if something has flagged it as done.
A simple hack to debug anonymous blocks - call the debugger explicitly before the line you want to examine.
function foo().then(s => {
... some code
debugger // here your code will break.
someVariableIwantToExamine
}

setTimeout not working in windows script (jscript)

When I try to run the following code in my program
setTimeout("alert('moo')", 1000);
I get the following error
Error: Object expected
Code: 800A138F
Source: Microsoft JScript runtime error
Why? Am I calling the wrong function? What I want to do is delay the execution of the subsequent function.
It sounds like you're using setTimeout in a non-browser-based script (Windows Script Host or similar). You can't do that. You can, however, use WScript.Sleep to suspend your script briefly, with which you can achieve a similar effect. Also, alert is not a WSH function; you may want WScript.Echo. More on the WSH reference on MSDN.
setTimeout is a method of the window object provided by web browsers. It's not available to scripts running on Windows Script Host. Those scripts have a single thread of execution from start to finish and have no delay timers.
If you want to pause script execution you can use the Sleep method of the WScript object.
I needed WSH to behave like similar code in browser that uses setTimeout, so here's what I came up with.
Just have your single thread execute everything in a queue. You can keep adding to the queue. The program will only terminate when no functions are left in the queue.
It doesn't support strings for eval, just functions.
function main() {
Test.before();
_setTimeout(Test.timeout1, 1000);
_setTimeout(Test.timeout2, 2000);
_setTimeout(Test.timeout3, 500);
_setTimeout(Test.error, 2001);
Test.after();
}
var Test = function() {
var ld = "---- ";
var rd = " ----";
return {
before : function() {
log(ld + "Before" + rd);
},
after : function() {
log(ld + "After" + rd);
},
timeout1 : function() {
log(ld + "Timeout1" + rd);
},
timeout2 : function() {
log(ld + "Timeout2" + rd);
},
timeout3 : function() {
log(ld + "Timeout3" + rd);
},
error : function() {
log(ld + "error" + rd);
errorFunc();
}
};
}();
var FuncQueue = function() {
var funcQueue = [];
function FuncItem(name, func, waitTil) {
this.name = name;
this.func = func;
this.waitTil = waitTil;
}
return {
add : function(func, name, waitTil) {
funcQueue.push(new FuncItem(name, func, waitTil));
},
run : function() {
while (funcQueue.length > 0) {
var now = new Date().valueOf();
for ( var i = 0; i < funcQueue.length; i++) {
var item = funcQueue[i];
if (item.waitTil > now) {
continue;
} else {
funcQueue.splice(i, 1);
}
log("Executing: " + item.name);
try {
item.func();
} catch (e) {
log("Unexpected error occured");
}
log("Completed executing: " + item.name);
break;
}
if (funcQueue.length > 0 && i > 0) {
if (typeof (WScript) != "undefined") {
WScript.Sleep(50);
}
}
}
log("Exhausted function queue");
}
}
}();
function _setTimeout(func, delayMs) {
var retval = undefined;
if (typeof (setTimeout) != "undefined") {
retval = setTimeout(func, delayMs); // use the real thing if available
} else {
FuncQueue.add(func, "setTimeout", new Date().valueOf() + delayMs);
}
return retval;
}
var log = function() {
function ms() {
if (!ms.start) {
ms.start = new Date().valueOf();
}
return new Date().valueOf() - ms.start; // report ms since first call to function
}
function pad(s, n) {
s += "";
var filler = " ";
if (s.length < n) {
return filler.substr(0, n - s.length) + s;
}
return s;
}
return function(s) {
if (typeof (WScript) != "undefined") {
WScript.StdOut.WriteLine(pad(ms(), 6) + " " + s);
} else {
// find a different method
}
}
}();
FuncQueue.add(main, "main");
FuncQueue.run();
For anybody who is searching for the alert function to work in a stand-alone script (Windows Script Host environment), I recommend checking out jPaq's alert function which is documented here and downloadable here. I have definitely found this new library to be helpful for my stand-alone scripts.

Categories

Resources