var change detect in html by jquery - javascript

I have a clock script and everything is fine, but I want to detect when the minutes change and add to this action some animation with jQuery, for example fadeToggle.
Can you tell me how can I detect the time change?
This is my script:
window.setInterval(function updateClock() {
var currentTime = new Date();
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
$.ajax({
success:function (clock) {
document.getElementById("hour").firstChild.nodeValue = currentHours;
document.getElementById("minutes").firstChild.nodeValue = currentMinutes;
}
});
if (currentMinutes.length == 1) {
currentMinutes = "0" + currentMinutes;
}
}, 500);

Related

Show clock/time increment from javascript

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>

Configuring Mediawiki UTCLiveClock Gadget

I am working with MediaWiki's UTCLiveClock.js and I am trying to configure it to put out a display time in PST/PDT. I thought I fixed the problem, however when midnight UTC hit (00:00:00) it changed my time output to 0-7:00:00. I need to to display properly so that when UTC 00:00:00 - 07:00:00 occurs, my time display doesn't look a mess. The gadget I am using through mediawiki can be found at https://www.mediawiki.org/wiki/MediaWiki:Gadget-UTCLiveClock.js
Yes, I'm a noob. I don't have any formal programming knowledge. I'm just trying to build a wiki for a game whose server exists in PST/PDT and running into this problem. Googling keyword searches for the last 3 hours has gotten me nowhere. Please help.
*/
/*global mw, $, UTCLiveClockConfig:true */
mw.loader.using(['mediawiki.util', 'mediawiki.api', 'mediawiki.notify']).then( function () {
var $target;
function showTime( $target ) {
var now = new Date();
var hh = now.getUTCHours();
var mm = now.getUTCMinutes();
var ss = now.getUTCSeconds();
var time = ( hh < 10 ? '0' + hh : hh ) + ':' + ( mm < 10 ? '0' + mm : mm ) + ':' + ( ss < 10 ? '0' + ss : ss );
$target.text( time );
var ms = now.getUTCMilliseconds();
setTimeout( function () {
showTime( $target );
}, 1100 - ms );
}
function liveClock() {
mw.util.addCSS( '#utcdate a { font-weight:bolder; font-size:120%; }' );
if ( !window.UTCLiveClockConfig ) {
UTCLiveClockConfig = {};
}
var portletId = UTCLiveClockConfig.portletId || 'p-personal';
var nextNode = UTCLiveClockConfig.nextNodeId ? document.getElementById( UTCLiveClockConfig.nextNodeId ) : undefined;
var node = mw.util.addPortletLink(
portletId,
mw.util.getUrl( null, { action: 'purge' } ),
'',
'utcdate',
null,
null,
nextNode
);
if ( !node ) {
return;
}
$( node ).on( 'click', function ( e ) {
new mw.Api().post( { action: 'purge', titles: mw.config.get( 'wgPageName' ) } ).then( function () {
location.reload();
}, function () {
mw.notify( 'Purge failed', { type: 'error' } );
} );
e.preventDefault();
} );
showTime( $( node ).find( 'a:first' ) );
}
$( liveClock );
} );
edit:
the way i originally fixed the problem is by putting a -7 in the hours section:
var hh = now.getUTCHours()-7;
It looks this is very simple Gadget limited to time in UTC. There are few options.
Find better script with support for time zones.
Write own script based on this one.
To write own script, there is critical part.
function get_PST_PDT_offset() {
/* You have to rewrite this function from time to time. */
var now = new Date();
var change = new Date(2016, 11, 5, 19, 0); /* 2016-11-06 2:00 PST */
if (now >= change) {
return -8;
} else {
return -7;
}
}
function showTime( $target ) {
var now = new Date();
var hh = now.getUTCHours();
var offset = get_PST_PDT_offset();
hh = (hh + offset + 24) % 24;
var mm = now.getUTCMinutes();
/* ... */

Why this Js / jquery code uses %70 of CPU?

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

new Date return NaN or a wrong time starting from server date()

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

Random .HTML, how to make it stop

I have a pool of 23 different .html files, and I need to access them randomly. That part was easy, but I need them to link to a different page after 40 of these pages have been shown. How can I do this?
var startTime = new Date();
Mousetrap.bind('e', function () {
var endTime = new Date();
var timeSpent = (endTime - startTime);
alert("Correct " + timeSpent + "miliseconds");
window.location.href = loft;
})
Mousetrap.bind('i', function() {
var endTime = new Date();
var timeSpent = (endTime - startTime);
$('img').css('display','block')
alert("Incorrecto " + timeSpent + "milisegundos");
})
var loft= Math.floor((Math.random()*40)+1);
Mousetrap is a js library that alows me to link key strokes to different functions. This is a social psycology study on reaction time.
Set a counter in a cookie so you can keep state of it after you change the window location. A good plugin to use for managing cookies is this guy: https://github.com/carhartl/jquery-cookie though you could also write some simple functions to set / unset cookies like so Set cookie and get cookie with JavaScript
Something to this effect:
var counter = $.cookie("counter");
if (counter == undefined){
counter = 0;
}
var startTime = new Date();
Mousetrap.bind('e', function () {
if (counter < 40){
var endTime = new Date();
var timeSpent = (endTime - startTime);
alert("Correct " + timeSpent + "miliseconds");
$.cookie("counter", ++counter);
window.location.href = loft;
}else{
//do stuff to show your thank you page
}
})
Mousetrap.bind('i', function() {
var endTime = new Date();
var timeSpent = (endTime - startTime);
$('img').css('display','block')
alert("Incorrecto " + timeSpent + "milisegundos");
})
var loft= Math.floor((Math.random()*40)+1);

Categories