socket.on doesn't fire the first time - javascript

Why doesn't this fire the first time? I'm not sure I understand this, please help! When I run pause() the second time, then it fires. Not sure what i'm doing wrong here.
this.pause = function (stopwatch){
this.stopwatch = stopwatch;
socket.emit('pauseTime'); //server does fire "paustime"
// this doesn't fire
socket.on('pauseTimeClock', function(data){
stopWatchClock.setPausedTime(data.time);
$('.pauseTime').html(data.time.replace(/(\d)/g, '<span>$1</span>'))
console.log(stopWatchClock.pausedTime);
});
this.stopwatch.changeState(this.stopwatch.getPauseState());
}
server code
socket.on('pauseTime', function () {
//stop broadcasting countDown time
clearInterval(timeinterval);
var pausedTime = moment();
function pauseTimeClock() {
var timeDiffHour = moment().hour() - pausedTime.hour();
var timeDiffMinute = moment().minute() - pausedTime.minute();
var timeDiffSec = moment().second();
var displayTime = timeDiffHour + ":" + timeDiffMinute + ":" + timeDiffSec;
socket.broadcast.emit("pauseTimeClock", { time: moment(displayTime, 'hhmm').format('HH:mm') });
console.log(timeDiffHour);
console.log(timeDiffMinute);
}
setInterval(pauseTimeClock, 1000);
})

Related

How to create a countdown that runs in the background using JavaScript?

I want to create a 3 hours countdown that runs in the background and repeats when it reaches 00:00:00. How can I do it using HTML and javascript? Thank you!
You can use Web Worker:
Run in background
No throttled ( settimeout-setinterval-on-inactive-tab )
// index.html
<div id="box">60</div>
<script>
let box = document.getElementById('box');
let worker = new Worker('countdown.js');
worker.postMessage(60);
worker.onmessage = function (event) {
box.innerHTML = event.data;
}
</script>
// countdown.js
onmessage = function (e) {
let num = e.data;
let count = setInterval(function () {
postMessage(--num);
if (num <= 0) {
clearInterval(count);
close();
}
}, 1000);
}
For background countdown. I think the big issue that you need to face is when you are leave the page or open a new tabs. right?
Do you want to make the countdown work even the tab is not active?
maybe requestAnimationFrame is helpful for you.
function showTime() {
remainingTime = getRemainingTime(endTime);
var seconds = pad((remainingTime / 1000));
console.log('remain time is: ', seconds + " sec")
if (remainingTime >= 1000) {
window.requestAnimationFrame(showTime);
} else {
console.log('Time up!!!')
}
}
function getRemainingTime(deadline) {
var currentTime = new Date().getTime();
return deadline - currentTime;
}
function pad(value) {
var sl = (""+Math.floor(value)).length;
if(sl > 2){
return ('0' + Math.floor(value)).slice(-sl);
}
return ('0' + Math.floor(value)).slice(-2);
}
endTime = new Date().getTime() + 1000*60;
window.requestAnimationFrame(showTime);
Demo here: https://codepen.io/quanhv/pen/oNZWxvB

Calculating time after pressing button (javascript)

I'm trying to make a reaction test website just for fun, but I don't know how to calculate the time taken between button presses.
I found this
var startTime;
function startButton() {
startTime = Date.now();
}
function stopButton() {
if (startTime) {
var endTime = Date.now();
var difference = endTime - startTime;
alert('Reaction time: ' + difference + ' ms');
startTime = null;
} else {
alert('Click the Start button first');
}
}
but it only works for 2 buttons (I only want one). So I tried making a function, something like
function calculateTime(){
startButton();
stopButton();
}
but of course, it doesn't work since it will stop the timer immediately. Any way to get around it?
Use a single function that checks whether startTime has been set or not. If it hasn't been set, it sets it; otherwise, it reports the time difference.
let startTime = null;
const button = document.querySelector("#timer");
button.addEventListener("click", startStop);
const output = document.querySelector("#output");
function startStop() {
if (startTime) {
var endTime = Date.now();
var difference = endTime - startTime;
output.innerText = 'Reaction time: ' + difference + ' ms';
startTime = null;
button.innerText = "Start Timer";
} else {
startTime = Date.now();
button.innerText = "Stop Timer";
output.innerText = "";
}
}
<button id="timer">Start Timer</button><br>
<div id="output"></div>
You were close. You need to declare the start time outside of the function so that it persists between function calls and then use the else section of the if statement to set it.
let startTime;
document.querySelector("button").addEventListener("click", startStop);
function startStop() {
if (startTime) {
console.log("Clock stopped");
var endTime = Date.now();
var difference = endTime - startTime;
alert('Reaction time: ' + difference + ' ms');
startTime = null;
} else {
startTime = Date.now();
console.log("Clock started");
}
}
<button>Start/Stop</button>
You can use performace.now() or console.time to calucalte time after press button.
var performance = window.performance;
var t0 = performance.now();
------your function--------
var t1 = performance.now();
console.log("This function took " + (t1 - t0) + " milliseconds.")
function a() {
console.time("buttontimer");
... your function ...
var dur = console.timeEnd("buttontimer"); // NOTE: dur only works in FF
}

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

Repeating setTimeout

I am trying to repeat setTimeout every 10 seconds. I know that setTimeout by default only waits and then performs an action one time. How can I repeat the process?
setTimeout(function() {
setTimeout(function() {
console.log("10 seconds");
}, 10000);
}, 10000);
Maybe you should use setInterval()
setInterval() is probably what you're looking for, but if you want to do get the same effect with setTimeout():
function doSomething() {
console.log("10 seconds");
setTimeout(doSomething, 10000);
}
setTimeout(doSomething, 10000);
Or if you don't want to declare a separate function and want to stick with a function expression you need to make it a named function expression:
setTimeout(function doSomething() {
console.log("10 seconds");
setTimeout(doSomething, 10000);
}, 10000);
(Or use arguments.callee if you don't mind using deprecated language features.)
according to me setInterval() is the best way in your case.
here is some code :
setInterval(function() {
//your code
}, 10000);
// you can change your delay by changing this value "10000".
Unlike the answers provided by #nnnnnn and #uzyn I discourage you from making use of setInterval for reasons elaborated in the following answer. Instead make use of the following Delta Timing script:
function DeltaTimer(render, interval) {
var timeout;
var lastTime;
this.start = start;
this.stop = stop;
function start() {
timeout = setTimeout(loop, 0);
lastTime = + new Date;
return lastTime;
}
function stop() {
clearTimeout(timeout);
return lastTime;
}
function loop() {
var thisTime = + new Date;
var deltaTime = thisTime - lastTime;
var delay = Math.max(interval - deltaTime, 0);
timeout = setTimeout(loop, delay);
lastTime = thisTime + delay;
render(thisTime);
}
}
The above script runs the given render function as close as possible to the specified interval, and to answer your question it makes use of setTimeout to repeat a process. In your case you may do something as follows:
var timer = new DeltaTimer(function (time) {
console.log("10 seconds");
}, 10000);
var start = timer.start();
const myFunction = () => {
setTimeout(() => {
document.getElementById('demo').innerHTML = Date();
myFunction();
}, 10000);
}
Easiest, but not efficient way!
Here is a function using setTimeout that tried to call itself as close as it can to a regular interval. If you watch the output, you can see the time drifting and being reset.
<script type="text/javascript">
function Timer(fn, interval) {
this.fn = fn;
this.interval = interval;
}
Timer.prototype.run = function() {
var timer = this;
var timeDiff = this.interval;
var now = new Date(); // Date.now is not supported by IE 8
var newInterval;
// Only run if all is good
if (typeof timer.interval != 'undefined' && timer.fn) {
// Don't do this on the first run
if (timer.lastTime) {
timeDiff = now - timer.lastTime;
}
timer.lastTime = now;
// Adjust the interval
newInterval = 2 * timer.interval - timeDiff;
// Do it
timer.fn();
// Call function again, setting its this correctly
timer.timeout = setTimeout(function(){timer.run()}, newInterval);
}
}
var t = new Timer(function() {
var d = new Date();
document.getElementById('msg').innerHTML = d + ' : ' + d.getMilliseconds();
}, 1000);
window.onload = function() {
t.run();
};
</script>
<span id="msg"></span>
Using jQuery, this is what you could do:
function updatePage() {
var interval = setTimeout(updatePage, 10000); // 10' Seconds
$('a[href]').click(function() {
$(this).data('clicked', true);
clearInterval(interval); // Clears Upon Clicking any href Link
console.log('Interval Cleared!');
});
// REPLACE 'YOUR_FUNCTION_NAME' function you would like to execute
setTimeout(YOUR_FUNCTION_NAME, 500);
} // Function updatePage close syntax
updatePage(); // call the function again.

Categories

Resources