I'm using below code block to update my progress bar and some other things. But something is wrong. When this page loaded my cpu works like crazy. I stop it after N seconds so after 5 seconds everything must finish. Am I wrong?
var start = new Date();
var maxTime = 5000;
var maxTimeSec = maxTime / 1000; //convert ms to sec : 20000 / 1000 = 20 sec
var timeoutVal = Math.floor( maxTime / maxTimeSec ); //every 1 second
var counter = 0;
var tt = setInterval(function(){ animateUpdate() },1000);
//Call function
animateUpdate();
//Check is user logined
function isLogined(){
userId = $("#userInfo").attr("data-user") ;
userId = parseInt(userId);
var logined = false;
if(userId > 0){
logined = true;
}
return logined;
}
//send some data to somewhere
function sendStat(){
var lang = $("#langCode").attr("data-lang");
var url = $("#pageUrl").attr("data-pageUrl");
var title = $("#pageTitle").attr("data-pageTitle");
var user = $("#user").attr("data-user");
$.ajax({
type: "POST",
url: "/actions/setStats.php",
data: {
"url" : url,
"langCode" : lang,
"title" : title,
"user" : user
},
success: function(res){
console.log(res);
}
});
}
//My timer
function animateUpdate() {
var now = new Date();
var timeDiff = now.getTime() - start.getTime();
//var sec = maxTimeSec - Math.round( (timeDiff/maxTime) * maxTimeSec );
var perc = Math.round( (timeDiff/maxTime)*100);
//console.log(perc);
if(counter > maxTimeSec) {
clearInterval(tt);
var bottomDiv = $('#bottomDiv');
bottomDiv.show();
if( isLogined() ){
bottomDiv.text("Congratulations. You're lucky to read this article. We've updated your score.");
}else{
bottomDiv.text("Congratulations. You're lucky to read this article. If want to count your score you must login :)");
}
sendStat();
} else {
$('#timerProgress').css("width", perc + "%");
$('#timerCountdown').text(perc + "%");
//setTimeout(animateUpdate, timeoutVal);
counter++;
}
}
Maybe you should try using jQuery.animate() with callbacks?
Example:
http://codepen.io/anon/pen/JdMNem
Related
I tried to show/increment the only time(Hours, Minutes and Seconds) like a timer from getting server side, but it's not working for me.
For this I tried below code.
Can you please help me to run the specified time (Server Time) to run as Timer.
What I have tried:
c#
ScriptManager.RegisterStartupScript(Page, this.GetType(), "close", "OnRunnTimer("+0.21023+");", true);
// JS COde
//Server time I am sending serverTimeP = 0.21023
function OnRunnTimer(timeP) {
setInterval(function () { runJSTimer(timeP); }, 1000);
}
function runJSTimer(serverTimeP) {
var d = new Date();
d.setHours(serverTimeP);
var hours = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
lblJsTimer.SetText(hours + ":" + min + ":" + sec);
}
Can you please help on this.
I'm not sure if I understood, but this is my example of solution to what I think to be your issue.
<body>
<h2 id="timeLabel">Time Label!</h2>
<script type="text/javascript">
var hours = 0;
var min = 0;
var sec = 0;
var serverTime = '2021-02-17T14:34:14.426Z'; // server time example in ISO format
var refreshTimeLabel = function(){
document.getElementById("timeLabel").innerHTML = hours + ":" + min + ":" + sec;
}
var refreshVariables = function () {
var serverTimeDate = new Date(serverTime);
var updatedServerTimeInMilliseconds = serverTimeDate.getTime() + (1000);
var updatedServerTimeDate = new Date(updatedServerTimeInMilliseconds);
serverTime = updatedServerTimeDate.toISOString();
hours = updatedServerTimeDate.getHours();
min = updatedServerTimeDate.getMinutes();
sec = updatedServerTimeDate.getSeconds();
}
var startTimer = function() {
setInterval(function () {
refreshVariables();
refreshTimeLabel();
}, 1000);
}
startTimer();
</script>
</body>
Variant for multiple rows
<body>
<h2 id="timeLabel">Time Label!</h2>
<script type="text/javascript">
var serverTimes = ['2021-02-17T16:34:45.426Z', '2021-02-17T14:54:14.426Z', '2021-02-17T14:00:00.426Z']; // server time array example in ISO format
var refreshServerTimeByIndex = function (index) {
var serverTime = serverTimes[index];
var serverTimeDate = new Date(serverTime);
var updatedServerTimeInMilliseconds = serverTimeDate.getTime() + (1000);
var updatedServerTimeDate = new Date(updatedServerTimeInMilliseconds);
serverTimes[index] = updatedServerTimeDate.toISOString();
}
var refreshServerTimes = function(){
var i;
for(i = 0; i < serverTimes.length; i++){
refreshServerTimeByIndex(i);
}
}
var getTimeTextByDateISO = function(dataISO){
var date = new Date(dataISO);
var hours = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
return hours + ":" + min + ":" + sec;
}
var refreshTimeLabel = function(){
var textLabel = "";
var i;
for(i = 0; i < serverTimes.length; i++){
textLabel += " | " + getTimeTextByDateISO(serverTimes[i]);
}
document.getElementById("timeLabel").innerHTML = textLabel;
}
var startTimer = function() {
setInterval(function () {
refreshServerTimes();
refreshTimeLabel();
}, 1000);
}
startTimer();
</script>
</body>
This code executes the "Click" function, but only one time. I would like it to repeated the click function until the timeout occurs.
I wanted to try setInterval instead of setTimeout, but was afraid I would create a race condition.
var M = 12; // january=1
var d = 29; // 1st=1
var h = 11; // 24h time
var m = 12;
var s = 0;
// How long after the target to stop clicking, in milliseconds.
var duration = 100000;
// How long prior to the start time to click, in milliseconds, to
// account for network latency.
var networkLatency = 150;
// HTML ID of the button to click.
var element = "btnbookdates";
// =====================================
// End configuration section
// =====================================
function getMillisecondsLeft() {
var nowDate = new Date();
var targetDate = new Date(y,M-1,d,h,m,s);
return targetDate - nowDate;
}
function click() {
var button = document.getElementById('btnbookdates');
if ( button ) {
window.console.log('clicked at '+getMillisecondsLeft());
button.click();
} else {
window.console.log('nothing to click at '+getMillisecondsLeft());
}
}
if (getMillisecondsLeft() > 0) {
window.console.log('queueing at '+getMillisecondsLeft());
setTimeout(click, getMillisecondsLeft() - networkLatency);
} else if (-getMillisecondsLeft() <= duration) {
click();
} else {
window.console.log('all done at '+getMillisecondsLeft());
}```
If I understood your question correctly, you want the click to stop when everything is done, i.e the else part at the end. You could try something like this:
var M = 12; // january=1
var d = 29; // 1st=1
var h = 11; // 24h time
var m = 12;
var s = 0;
// How long after the target to stop clicking, in milliseconds.
var duration = 100000;
// How long prior to the start time to click, in milliseconds, to
// account for network latency.
var networkLatency = 150;
// HTML ID of the button to click.
var element = "btnbookdates";
// =====================================
// End configuration section
// =====================================
function getMillisecondsLeft() {
var nowDate = new Date();
var targetDate = new Date(y,M-1,d,h,m,s);
return targetDate - nowDate;
}
function click() {
var button = document.getElementById('btnbookdates');
if ( button ) {
window.console.log('clicked at '+getMillisecondsLeft());
button.click();
} else {
window.console.log('nothing to click at '+getMillisecondsLeft());
}
}
var timer ={};
if (getMillisecondsLeft() > 0) {
window.console.log('queueing at '+getMillisecondsLeft());
timer = setInterval(click, getMillisecondsLeft() - networkLatency);
} else if (-getMillisecondsLeft() <= duration) {
click();
} else {
clearInterval(timer);
window.console.log('all done at '+getMillisecondsLeft());
}
I have a function called save with this code, it's meant to save data from a timer.
The class with the Model is this:
var Schema = mongoose.Schema;
var Timer = new Schema({
Time: {type: Number},
Desc: {type: String},
Doc: {type: String}
});
Timer.statics.findByDesc = function(value, callback){
this.find({ Desc: {"$regex": value, "$options": "i"}}, callback);
}
Timer.statics.findByDoc = function(value, callback) {
this.find({ Doc: { "$regex": value, "$options": "i" }}, callback);
}
Timer.statics.findAll = function(callback){
this.find({}, callback);
}
module.exports = mongoose.model('Timer', Timer);
the model is defined by this code which is imported with:
var Timer = require('./../../models/timer');
but I'm testing it with constants in a function which is called by clicking button, this is the code inside the function:
var newTimer = new Timer({
Time: 6000, Desc: "My first timertest!", Doc: "Test's Dossier"
});
newTimer.save();
however with trial and error I have figured out that it never calls newTimer.save(), it seems to get stuck somewhere without ever leaving the var newTimer = new Timer() function.
I have tried my Timer Model code in other files with code like:
/**
* Created by kevin on 08/03/2016.
*/
var Timer = require('../models/timer'),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/legalapp');
mongoose.connection.on('open', function() {
console.log('Mongoose connected.');
});
var newTimer = new Timer({
Time: 5000, Desc: "My first timertest!", Doc: "Test's Dossier"
});
console.log(newTimer.Time);
console.log(newTimer.Desc);
console.log(newTimer.Doc);
newTimer.save();
mongoose.connection.close();
and this did work, so after 3 hours of trying, I'm going crazy, so I came here.
I am using javascript, nodeJS, jquery and mongoose in my project.
Here is the entire file:
var timers = [], Timer = require('./../../models/timer');
function timer(id){
this.id = id;
this.running = false;
this.start = new Date();
this.current = new Date();
this.paused = new Date();
this.timed = 0;
this.desc = "";
this.pauseTime = 0;
this.pauseTimeBuffer = 0;
this.prevTimed = 0;
this.first = true;
this.h = Math.floor(this.timed / 1000 / 60 / 60);
this.timed -= this.h * 1000 * 60 * 60;
this.h = checkTime(this.h);
this.m = Math.floor(this.timed / 1000 / 60);
this.timed -= this.m * 1000 * 60;
this.m = checkTime(this.m);
this.s = Math.floor(this.timed / 1000);
this.timed -= this.s * 1000;
this.s = checkTime(this.s);
}
function startTime(timer){
if(!timer.running) {
if (timer.first) {
timer.start = new Date();
timer.first = false;
}
timer.running = true;
time(timer);
}
}
function stopTime(timer){
if(timer.running) {
if (timer.pauseTime === 0) {
timer.paused = new Date();
} else {
timer.paused = new Date();
timer.pauseTimeBuffer = timer.pauseTime;
}
timer.running = false;
time(timer);
}
}
function save(timer){
//stopTime(timer);
/*var desc = prompt("Enter the description of this task", timer.desc);
var dossier = prompt("What dossier does this timer belong to?");
var current = new Date();
var timed = timer.current - timer.start;
timed -= timer.pauseTime;
*/
var newTimer = new Timer();
newTimer.Time = 6000;
newTimer.Desc = "My first timertest!";
newTimer.Doc = "Test's Dossier";
newTimer.save();
alert("yay");
}
function time(timer) {
if(timer.running) {
var name = '#timer' + timer.id;
var $time = $('' + name);
timer.current = new Date();
timer.timed = timer.current - timer.start;
timer.timed -= timer.pauseTime;
timer.h = Math.floor(timer.timed / 1000 / 60 / 60);
timer.timed -= timer.h * 1000 * 60 * 60;
timer.h = checkTime(timer.h);
timer.m = Math.floor(timer.timed / 1000 / 60);
timer.m = checkTime(timer.m);
timer.timed -= timer.m * 1000 * 60;
timer.s = Math.floor(timer.timed / 1000);
timer.timed -= timer.s * 1000;
timer.s = checkTime(timer.s);
$time.html("" + timer.h + ":" + timer.m + ":" + timer.s);
//var t = setTimeout(time(timer), 10);
}else{
timer.current = new Date();
timer.pauseTime = timer.current - timer.paused;
timer.pauseTime += timer.pauseTimeBuffer;
//var t = setTimeout(time(timer), 10);
}
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
function init(timer){
var name = "#timer" + timer.id;
var $time = $('' + name)
$time.html("" + timer.h + ":" + timer.m + ":" + timer.s);
run();
}
function run(){
for(i = 0; i < timers.length;i++){
var timer = timers[i];
setTimeout(time(timer), 10);
}
setTimeout(run, 10);
}
function action(id, action){
if(action === "start"){
var t = timers[id - 1];
startTime(t);
}else if(action === "stop"){
var t = timers[id - 1];
stopTime(t);
}else if(action === "save"){
var t = timers[id - 1];
save(t);
}
}
function stopAll(){
for(i = 0; i < timers.length; i++){
var t = timers[i];
stopTime(t);
}
}
function add(){
stopAll();
var number = timers.length + 1;
var starttext = '"start"';
var savetext = '"save"';
var stoptext = '"stop"';
var newTimer = new timer(number);
timers.push(newTimer);
$('#timers').append("<br/>" +
"<h1>Timer " + number + "</h1>" +
"<div id=" + 'timer' + number + ">Test</div>" +
"<button onclick='action(" + number + ", " + starttext + ")" + "'>Start</button>" +
"<button onclick='action(" + number + ", " + stoptext + ")" + "'>Stop</button>" +
"<button onclick='add()'>Add</button>" +
"<button onclick='action(" + number + ", " + savetext + ")" + "'>Save</button>" +
"<p class='description' id='" + 'desc' + number + "'>Click here to enter a description</p>");
$(".description").click(function(){
var text = prompt("Please enter your description here");
if(text === ""||text === null) {
$(this).html("Click here to enter a description");
}else{
$(this).html(text);
timers[number - 1].desc = text;
}
});
init(newTimer);
setTimeout(startTime(newTimer));
}
Save is the function that I have problems with.
You cannot make client side Javascript and server side Javascript coexist at the same file. Jquery/HTML code runs inside a browser and nodejs/express runs inside a server.
Reference to Client-Server concept
https://softwareengineering.stackexchange.com/questions/171203/what-are-the-differences-between-server-side-and-client-side-programming
Some good reference to work with NodeJS
calling a server side function from client side(html button onclick) in node.js
Sample app
https://github.com/jmhdez/Nodejs-Sample
I have this recursive function which is giving me some problems. It needs to be runned like 20.000 times, but when it loops many times the browser crashes. Any help is appreciated
var valid = 0, id = 0;
$(document).ready(function() {
$("#fetch").submit(function(event) {
event.preventDefault();
var selected = $(this).find("#site option:selected");
var pieces = selected.text().split("(");
var sitename = pieces[0];
var numbers = pieces[1].slice(0,-1).split("/");
var fetched = numbers[0]; var total = numbers[1];
var members = $(this).find("#members").val();
var time = $(this).find("#wait").val() * 1000;
wait = (time == 0) ? 800 : time;
$("progress").prop("value", 0).prop("max", members * 2).fadeIn();
valid = 0;
function fetchMember(id) {
id++;
$.post("script.php", $("#fetch").serialize() + "&id=" + id )
.done(function(data) {
console.clear();
isUser = ($(data).text().indexOf("Invalid User") == -1);
if (isUser) valid++;
if(valid < members) setTimeout(function(){ fetchMember(id) }, wait);
if (isUser) {
progress();
fetched++;
selected.text(sitename+"("+fetched+"/"+total+")"); //Updating numbers of fetched profiles on the frontend
username = $(data).find(".normal").text() || $(data).find(".member_username").text() || $(data).find("#username_box h1").text();
$(data).find("dt").each(function() {
var text = $(this).text();
if (text == 'Location') country = $(this).next("dd").text();
});
$.post("save.php", { username: username } )
.done(function(data) {
$("#test").append(id+" "+data + "<br />");
progress();
});
}
});
}
fetchMember(id);
});
});
The function needs to be repeated 20.000 times with a default interval of 800ms or even more like 10 minutes
This function isn't recursing, it's just using setTimeout to call itself again at some point in the future, which isn't the same as true recursion.
However, you're using a global variable passed into a function, this will be causing you scoping issues as it's passed as a copy. By passing the id in to the timed call, you're creating a closure, which at 20,000 times, may be causing you some issues.
That's 20,000 function calls you're pushing onto the stack. That is very memory-intensive.
Try if it is a memory issue but I don't see that looking at the code.
var valid = 0, id = 0;
$(document).ready(function() {
$("#fetch").submit(function(event) {
event.preventDefault();
var selected = $(this).find("#site option:selected");
var pieces = selected.text().split("(");
var sitename = pieces[0];
var numbers = pieces[1].slice(0,-1).split("/");
var fetched = numbers[0]; var total = numbers[1];
var members = $(this).find("#members").val();
var time = $(this).find("#wait").val() * 1000;
wait = (time == 0) ? 800 : time;
$("progress").prop("value", 0).prop("max", members * 2).fadeIn();
valid = 0;
fetchMember(id,selected,pieces,sitename,numbers,fetched,members,time,wait);
});
});
function fetchMember(id,selected,pieces,sitename,numbers,fetched,members,time,wait) {
id++;
$.post("script.php", $("#fetch").serialize() + "&id=" + id )
.done(function(data) {
console.clear();
isUser = ($(data).text().indexOf("Invalid User") == -1);
if (isUser) valid++;
if (isUser) {
progress();
fetched++;
selected.text(sitename+"("+fetched+"/"+total+")"); //Updating numbers of fetched profiles on the frontend
username = $(data).find(".normal").text() || $(data).find(".member_username").text() || $(data).find("#username_box h1").text();
$(data).find("dt").each(function() {
var text = $(this).text();
if (text == 'Location') country = $(this).next("dd").text();
});
$.post("save.php", { username: username } )
.done(function(data) {
$("#test").append(id+" "+data + "<br />");
progress();
if(valid < members) setTimeout(function(){ fetchMember(id,selected,pieces,sitename,numbers,fetched,members,time,wait) }, wait);
});
}
});
}
Memory leak references http://javascript.crockford.com/memory/leak.html ... jquery does not leak.
[Exhibit 4 - Leak test with a closure]
<html>
<head>
<script type="text/javascript">
function LeakMemory(){
var parentDiv = document.createElement("div");
parentDiv.onclick=function(){
foo();
};
parentDiv.bigString =
new Array(1000).join(new Array(2000).join("XXXXX"));
}
</script>
</head>
<body>
<input type="button"
value="Memory Leaking Insert" onclick="LeakMemory()" />
</body>
</html>
I'm trying to get server time at start and update it, cause i've to cotnrol some elements with real time. The problem is that if my serverTime doesn't have T the time is NaN on firefox and IE, but if i replace the empty space with T on chrome and IE i've a wrong time.
I now the work-around of replacing white space with T sucks but im outta of time :)
Thanks everybody
At start:
$tmpTime = date("Y-m-d H:i:s");
Head:
<script>
var serverTime = '<?=$tmpTime?>';
serverTime = serverTime.replace(" ", "T");
</script>
Script:
setInterval(function () {
console.log(serverTime);
var tmpTime = new Date(serverTime);
console.log(tmpTime);
var t = tmpTime.getTime();
t = t + 1000;
tmpTime = new Date(t);
serverTime = t;
if (tmpTime.getMinutes() < 10) {
var minutes = "0" + tmpTime.getMinutes();
} else {
var minutes = tmpTime.getMinutes();
};
newTime = tmpTime.getHours() + ":" + minutes;
$('#liveTime').text(newTime);
if ($("#program li[time-id='" + newTime + "'][class='alert']").length !== 0) {
alert("Lo streaming da te programmato sta per iniziare!");
$("#program li[time-id='" + newTime + "'][class='alert']").removeClass("alert");
}
titleToShow();
}, 1000);
function titleToShow() {
$("#program li").each(function () {
var prevTime = $(this).prev("li").attr("time-id");
var thisTime = $(this).attr("time-id");
var nextTime = $(this).next("li").attr("time-id");
currentTime = Date.parse('01/01/2011 ' + newTime);
prevTime = Date.parse('01/01/2011 ' + prevTime);
nextTime = Date.parse('01/01/2011 ' + nextTime);
thisTimeNew = Date.parse('01/01/2011 ' + thisTime);
if (currentTime >= thisTimeNew && currentTime < nextTime && currentTime > prevTime) {
title = $(this).find("p").text();
if (title != $("p#playingTitle").text()) {
$("p#playingTitle").text(title);
}
}
})
}
Don’t use a formated date, just pass the Unix timestamp value to the script (don’t forget to multiply it by 1000, because JS works with milliseconds).
var serverTime = <?php echo time(); ?>;
var tmpTime = new Date(serverTime * 1000);