How to delay a JavaScript JSON stream for one minute? - javascript

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.

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>

Javascript pausing timer woes... Can't calculate it

I've built a series of timers that are designed to be started, paused and resumed on cue. Numbers update dynamically on my page when the timer ticks up. The issue I'm having is figuring out how to get the timer to start from where it left off before I paused it. I can get it to restart from scratch, but I unsure how to take the paused Date.now() value, and work it into the formula to display the correct value. It will be something stupid that I just cant figure out.
function ticking2(num) {
//IF TIMER IS PAUSED CANCEL THE ANIMATION FRAME
if (timerObjArray[num].paused == true) {
timerObjArray[num].restartTime = Date.now();
cancelAnimationFrame(id);
} else if (timerObjArray[num].paused == false) {
timerObjArray[num].initialTime = Date.now()
if (timerObjArray[num].restartTime != 0) {
//THIS IS THE LINE WHERE I AM HAVING TROUBLE
timerObjArray[num].milli = ((timerObjArray[num].initialTime - timerObjArray[num].initialDate) - (timerObjArray[num].initialTime - timerObjArray[num].restartTime)) / 1000;
} else {
timerObjArray[num].milli = ((timerObjArray[num].initialTime - timerObjArray[num].initialDate ) / 1000);
}
//THIS FUNCTION TAKES THE MS VALUE AND CONVERTS IT TO HH:MM:SS
convert(num, timerObjArray[num].milli * 1000);
id = requestAnimationFrame(function() {
ticking2(num);
});
}
}
Thanks for the help.
I don't have enough information so, I made a simple implementation. You can look at this to help determine what you're missing. You're welcome to use it.
Timer fiddle
Utility:
var timer = (function() {
let _timers = {};
let pub = {
start : function(id) {
if(!_timers[id]) _timers[id] = {on:true, intervals:[{start:new Date()}] };
else if(_timers[id].on) throw 'timer is already started: ' + id;
else {
_timers[id].on = true;
_timers[id].intervals.push({start:new Date()});
}
},
stop : function(id) {
if(!_timers[id]) throw 'timer does not exist, cannot be stopped: ' + id;
else if(!_timers[id].on) throw 'timer is already stopped: ' + id;
else {
_timers[id].on = false;
let interval = _timers[id].intervals[_timers[id].intervals.length -1];
interval.stop = new Date();
interval.total = interval.stop - interval.start;
}
},
read : function(id) {
if(!_timers[id]) throw 'timer does not exist, cannot be read: ' + id;
let total = 0;
for(let i=0; i<_timers[id].intervals.length; i++) {
if(_timers[id].intervals[i].total) total += _timers[id].intervals[i].total;
else total += (new Date()) - _timers[id].intervals[i].start;
}
return { intervals:_timers[id].intervals, total: total };
},
delete: function(id) {
if(!_timers[id]) throw 'timer does not exist, cannot be deleted: ' + id;
delete _timers[id];
}
};
return pub;
})();
Example usage:
$('.start').on('click', function(){
timer.start(123);
});
$('.stop').on('click', function(){
timer.stop(123);
});
$('.clear').on('click', function(){
timer.delete(123);
$('input').val('');
});
setInterval(function(){
let result = null;
try//obviously not a great pattern
{
result = timer.read(123);
} catch(ex){}
if(result) {
$('input').val(result.total);
}
}, 35);

javascript, setInterval function starts counting not from 0

I have noticed, that my setInterval function starts counting from 1, and sometimes even from 10. But if i increase the interval to some 20 seconds, it starts counting correctly from 0. Subsequent counting is correct - adds one in every step, but the initial cnt value, if i reduce to internval to some 5 seconds, becomes wrong.
var stepProt = function () {
console.log('started stepProt constructor');
this.step = 20; //seconds
this.cnt = 0; //init counter, pointer to rtArr
};
stepProt.prototype.countingFnc = function () {
console.log('started stepFnc.prototype.countingFnc');
var msec = this.step*1000;
var that = this;
that.cnt=0;
this.nameToStop = window.setInterval( function () {
that.stepFnc(); }, msec );
}
stepProt.prototype.stepFnc = function() {
console.log (' 132 startedFnc rtG.prototype.stepFnc, this.cnt='+this.cnt ); //if interval is 5seconds, this.cnt usually starts from 1, but sometimes from 10, instead of starting from 0. All other steps are correct, +1 each time.
/* here there is some logics, which takes time */
this.cnt++;
};
var stepIn = new stepProt(); //instance
stepIn.stepFnc();
What could be the reason and how to resolve?
p.s.
Actually, i use this function before window onload. Maybe this is the reason?
I include many scripts before window.onload.
Later i make single script for window.onload functionality.
I put
var stepIn = new stepFnc(); //instance
stepIn.stepFnc();
before window onload, because if i use it in window.onload, for some reason, other functions does not understand stepIn instance as a global variable accessable everythere. Maybe it is because i use php template.
You should call stepIn.countingFnc(); to start the process. Another thing is that I'd change the name of the function stepFnc so it doesn't match with the constructor name for readability.
var stepFnc = function () {
console.log('started stepFnc constructor');
this.step = 20; //seconds
this.cnt = 0; //init counter, pointer to rtArr
};
stepFnc.prototype.countingFnc = function () {
console.log('started stepFnc.prototype.countingFnc');
var msec = this.step*1000;
var that = this;
that.cnt=0;
this.nameToStop = setInterval( function () {
that.triggerFnc(); }, msec );
}
stepFnc.prototype.triggerFnc = function() {
console.log (' 132 startedFnc rtG.prototype.stepFnc, this.cnt='+this.cnt ); //if interval is 5seconds, this.cnt usually starts from 1, but sometimes from 10, instead of starting from 0. All other steps are correct, +1 each time.
/* here there is some logics, which takes time */
this.cnt++;
};
var stepIn = new stepFnc();
stepIn.countingFnc();
Hope this helps. ;)
var stepFnc = function () {
console.log('started stepFnc constructor');
this.step = 1; //seconds
this.cnt = 0; //init counter, pointer to rtArr
};
stepFnc.prototype.countingFnc = function () {
console.log('started stepFnc.prototype.countingFnc');
var msec = this.step*1000;
var that = this;
that.cnt=0;
this.nameToStop = window.setInterval( function () {
that.stepFnc(); }, msec );
};
stepFnc.prototype.stepFnc = function() {
console.log (' 132 startedFnc rtG.prototype.stepFnc, this.cnt='+this.cnt ); //if interval is 5seconds, this.cnt usually starts from 1, but sometimes from 10, instead of starting from 0. All other steps are correct, +1 each time.
/* here there is some logics, which takes time */
this.cnt++;
};
var stepIn = new stepFnc();
stepIn.countingFnc();
Seems the reason is that i use setInterval in script not in window.onload, thus the first counter is wrong. I created function to check if javascript is loaded, and than i use boolen in setInterval to start counting only after the all javascript is loaded.
var loadIn - checks if javascript is loaded ,and sets loadIn.jsLoad =true.
if(loadIn.jsLoad) { that.stepFnc(); }
Code checking if
javascript is loaded : this.jsLoad = true (mainly i need this),
html is loaded : this.htmlLoad= true,
both js and html are loaded: this.bLoaded =true
console.log('loading check started' );
var loadProt = function () {
this.bLoaded = "";
this.checkLoadInt="";
this.jsLoadFnc="";
this.bDomainCheckPass = false; //assumes that domain is wrong
this.beforeunload = ""; //event
this.jsLoad = false;
this.htmlLoad = false;
this.bLoaded =false;
};
loadProt.prototype.checkLoadFnc = function() {
console.log('startedFnc checkLoadFnc');
this.htmlLoad = false;
this.jsLoad = false;
if(document.getElementById("bottomPreloadSpan")) { this.htmlLoad =true; }
this.jsLoad = this.jsLoadFnc();
console.log( 'htmlLoad='+this.htmlLoad +', jsLoad=' +this.jsLoad ) ;
this.bLoaded = this.htmlLoad && this.jsLoad;
if( this.bLoaded ) {
this.stopIntervalFnc();
}
};
loadProt.prototype.stopIntervalFnc = function() {
console.log('startedFnc stopIntervalFnc');
document.getElementById("preloadSpan").style.visibility = "hidden";
var preloadImg = document.getElementById('preloadImage');
preloadImg.parentNode.removeChild(preloadImg);
clearInterval(this.checkLoadInt);
this.bDomainCheckPass = this.checkAllowedDomains(); // i do not give it here
//this.evalStep();
if(this.bDomainCheckPass) {
console.log('ERROR right domain');
} else {
console.log('ERROR Wrong domain');
//window.location.assign loads a new document - to login page, saying you was redirected ....
}
}
var loadIn = new loadProt();
loadIn.checkLoadInt = window.setInterval(
function() { loadGIn.checkLoadFnc(); }, 1000 );
loadIn.jsLoadFnc = document.onreadystatechange = function () { return (document.readyState=='complete') ? true : false ; }
Counter function:
var stepProt = function () {
console.log('started stepFnc constructor');
this.step = 20; //seconds
this.cnt = 0; //init counter, pointer to rtArr
};
stepProt.prototype.countingFnc = function () {
console.log('started stepFnc.prototype.countingFnc');
var msec = this.step*1000;
var that = this;
that.cnt=0;
this.nameToStop = window.setInterval( function () {
if(loadIn.jsLoad) { that.stepFnc(); }
}, msec );
}
stepProt.prototype.stepFnc = function() {
console.log (' 132 started stepFnc, this.cnt='+this.cnt );
/* here there is some logics, which takes time */
this.cnt++;
};
var stepIn = new stepProt(); //instance
stepIn.countingFnc();

async and set timeout

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);
}

javascript settimeout not working inside recursive function

My script is as follows which should replay mouse image inside a div but settimeout is not working and there is no error in console also:
function play(data, value) {
var data = data;
function run() {
var nowTime;
var newdata = data.splice(0, 1); // after splice, data will be auto updated
if (newdata.length == 1) {
nowTime = newdata[0][6];
var timer = setTimeout(function() {
if (newdata[0][3] == '14') {
replay(newdata[0][0], newdata[0][1]);
}
preTime = nowTime;
// continue run next replay
run();
}, nowTime - preTime);
}
}
run();
}
Please help me. How to solve this issue.
thanks in advance
try this
var newdata;
var nowTime;
var preTime;
function play(data, value)
{
newdata= data.splice( 0, 1 ); // after splice, data will be auto updated
if ( newdata.length == 1 ) {
nowTime = newdata[0][6];
var timer = setTimeout("timer();",nowTime - preTime );
}
}
function timer()
{
if(newdata[0][3] == '14'){
replay( newdata[0][0], newdata[0][1]);
}
preTime = nowTime;
play();
}
play();

Categories

Resources