Countdown timer in javascript using setTimeout - c#

i'm creating a countdown timer using jquery, i refered to a few example here and came out with the following codes. The problem is the time doesn't show, and i can't figure out what is wrong. Been stuck for almost 2 hours..
back code
var day = 1; //countdown time
var start = player.LastActive; // Use UtcNow instead of Now
var endTime = start.AddDays(day); //endTime is a member, not a local variable
Timespan remainingTime = endTime - DateTime.UtcNow;
my javascript
var endTime = '<%= remainingTime%>';
var startTime = '<%= DateTime.UtcNow %>'
$(document).load(function () {
countDown(endTime);
});
function countDown(endTime) {
if (endTime > 0) {
var d = document.getElementById("countDiv");
d.innerHTML = endTime;
setTimeout(function () { countDown(endTime - 1); }, 1000);
}
}
my html
<div id="countDiv" style="float:left;margin-top: 13px; margin-left:5px;"></div>
my goal is to show how long more, for a player to get his daily move : which is a day after the players lastactive time. Can someone enlighten me..thank u

use $(window).load
or
$(document).ready
but not $(document).load
and as you seem to use jquery, you can do
$(document).ready(function () {
countDown(endTime);
});
function countDown(endTime) {
if (endTime > 0) {
$('#countDiv').text(secondsToTime(endTime));
setTimeout(function () { countDown(endTime - 1); }, 1000);
}
}
function secondsToTime(secs)
{
var hours = Math.floor(secs / (60 * 60));
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
return hours +':' + minutes + ':' + seconds;
}
for seconds to time, it's coming from
https://stackoverflow.com/a/6312999/961526 , you may take another version which you can find there.
see jsFiddle

Since your endtime is string in your javascript code, convert it integer first
try this
$(document).ready(function () {
countDown(parseInt(endTime));
});

ready, not load.
$(document).ready(function () {
countDown(endTime);
});

Or try this
$(function() {
countDown(endTime);
});
function countDown(parseInt(endTime)) {
if (endTime > 0) {
$('#countDiv').text(endTime);
setTimeout(function () { countDown(endTime - 1); }, 1000);
}
}

Related

Trying to implement timer and perform tasks every x seconds but the tasks seem to get delayed

I'm writing an app where a user specifies a length of time, length of an interval and a length of time in between intervals. I want to have a timer label showing the user the total time but then I also want to have a label showing the work status (recording if in the interval, break if between interval time and break end).
Heres an Example: Total time = 2 min, Interval = 20 seconds, Break = 10 seconds
In this example there will be 4 intervals. So from 0:00-0:19 I want to display "Recording" and then from 0:20-0:29 I want to display break and then from 0:30-0:49 I display "Recording" and 0:50-0:59 I display "Break" and so on. All while the timer counts the time.
So I thought this would be pretty straightforward but what seems to happen is the timer increments properly but after the 1st interval the label doesnt switch from break to recording until 0:31 or 0:32 so it looks a little delayed.
Here is the code I am using currently (Note obs is an object Im passing in that has data from user input).
int TotalInterval = obs.Interval + obs.Break;
int WorkingInterval = obs.Interval;
int NumberOfIntervals = (obs.Duration*60) / TotalInterval;
DateTime ObservationEnd = obs.DateCreated.AddMinutes(obs.Duration);
Timer.Text = "Starting Timer";
int minutes = 0;
int seconds = 0;
int InIntervalCounter = 0;
Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
// called every 1 second
Timer.Text = "Started";
if (ObservationEnd < DateTime.UtcNow)
{
Timer.Text = "Time Over";
Results.IsVisible = true;
return false;
}
else
{
seconds++;
InIntervalCounter++;
if (InIntervalCounter > WorkingInterval)
IntervalOrBreak.Text = "Break";
if (InIntervalCounter > TotalInterval)
{
IntervalOrBreak.Text = "Recording";
InIntervalCounter = 0;
}
Timer.Text = "Time: " + minutes + ":" + seconds.ToString("D2");
return true;
}
});
I'm pretty new to app development/xamarin so any help is greatly appreciated.
Try using simple Threads with Thead.sleep() like this:
final long delay_millis = 100;
Thread thread_something;
thread_something = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
long start_time = SystemClock.elapsedRealtime();
// Do some task
long time_need_for_delay = (start_time + delay_millis) - SystemClock.elapsedRealtime();
if(time_need_for_delay > 0)
thread_something.sleep(time_need_for_delay);
} catch (Exception e) { }
}
}
});
thread_something.start();
after the 1st interval the label doesnt switch from break to recording
until 0:31 or 0:32 so it looks a little delayed.
If you want to display break from 0:20-0:29 and display "Recording" from 0:30-0:49, I think the if statement should change to InIntervalCounter >= WorkingInterval and InIntervalCounter >= TotalInterval, InIntervalCounter > WorkingInterval may cause the 1 second delay.

C# Timer-Filter for Command

First of all, I am pretty new to coding. I am currently trying to program my Discord-bot and I ran into this issue:
I want to create a command with a timer on it, so everytime someone uses this command, the timer starts ticking and after the timer reached a certain amount of seconds, the user is able to use this command again. The command is a "joke-command" where everytime you use it, the bot tells you a joke.
Is there a way to implement this?
I currently have this:
//joke-integer
int jokeNumber;
jokeNumber = 0;
//joke-list
joke = new string[]
{
"aaa",
"bbb",
"ccc",
};
//joke-command
commands.CreateCommand("joke")
.Do(async e =>
{
jokeNumber = jokeNumber + 1;
if (jokeNumber.Equals(3))
{
jokeNumber = 0;
}
else
{
jokeNumber = jokeNumber + 0;
}
string jokePost = joke[jokeNumber];
await e.Channel.SendMessage(jokePost);
});
So this (^) just tells you a joke out of a list if you use the command "!joke" but I want that this command is only "enabled" if the timer passed for example 100 seconds.
You need to store the last time an user has requested the command, and then check this date every time a new command is requested.
Inside your class:
private static readonly ConcurrentDictionary<long, DateTimeOffset> UsersJokesLastCall = new ConcurrentDictionary<long, DateTimeOffset>();
When creating your command:
commands.CreateCommand("joke")
.Do(async e =>
{
var id = e.ChannelId; // example using channel id as unique key
var nowUtc = DateTimeOffset.UtcNow;
var canReturnJoke = true;
UsersJokesLastCall.AddOrUpdate(id, nowUtc, (key, oldValue) =>
{
var elapsed = nowUtc - oldValue; // check elapsed time
if(elapsed.TotalSeconds < 100)
{
canReturnJoke = false; // min time has not passed
return oldValue; // do not change the last joke time
}
return nowUtc; // update to current time
});
if(!canReturnJoke)
{
// return something to the user
await e.Channel.SendMessage("Try later");
return;
}
jokeNumber = jokeNumber + 1;
if (jokeNumber.Equals(3))
{
jokeNumber = 0;
}
else
{
jokeNumber = jokeNumber + 0;
}
string jokePost = joke[jokeNumber];
await e.Channel.SendMessage(jokePost);
});
You may need to further work on this code, but this should give you the overall approach.

How do I add TimeSpan in C# inside Loop?

Can anyone please tell me I need to add time with interval with in the for loop. This is my C# code.
var t1 = selectedTime.TimeOfDay;
t1 = 8.00 //assum time is 8.00
for (int i = 0; i <=5; i++) {
var duration = TimeSpan.FromMinutes(15);
var t3 = duration;
}
My output should be:
8.00
8.15
8.30
8.45
9.00
The gotcha in your original code is increment and persist the new value; in this snippet I updated the t1 variable:
var selectedTime = DateTime.Today.AddHours(8);
var t1 = selectedTime.TimeOfDay; //assume time is 8.00
for (int i = 0; i <=5; i++)
{
Console.WriteLine(t1);
t1 += TimeSpan.FromMinutes(15);
}
Try like this:
var t1 = DateTime.Now.TimeOfDay;
//t1 = 8.00 //assum time is 8.00
var duration = TimeSpan.FromMinutes(15);
Console.WriteLine(t1); // print current time
for (int i = 0; i <=4; i++)
{
t1 += duration; // add timespan 4 times
Console.WriteLine(t1);
}
You can add TimeSpan to the DateTime easily. You just need to make sure you are remembering the previous value or by increasing the time span (eg. 15 min, 30 min etc) in each loop cycle.
Alternatively, you could use the DateTime.AddMinutes() method:
DateTime t1 = DateTime.Now.AddHours(8);
for(int i = 0; i < 5; i++) {
Console.WriteLine(t1.AddMinutes(15 * i).ToString("HH:mm"));
}
TimeSpan is added using the + operator with another TimeSpan, for example, I can implement this 15 seconds interval loop using Linq as the following:
TimeSpan initialTimeSpan = new TimeSpan(0, 4, 2);
IEnumerable<TimeSpan> spans = Enumerable.Range(0, 5)
.Select(x => x * 15)
.Select(x => initialTimeSpan + TimeSpan.FromSeconds(x));
foreach (TimeSpan span in spans)
{
Console.WriteLine(span);
}
To add it to a DateTime use the Add method:
DateTime date = DateTime.Now;
TimeSpan initialTimeSpan = new TimeSpan(0, 4, 2);
date = date.Add(initialTimeSpan);
Or you can just add the period you wish without using TimeSpan by using the AddSeconds/AddMinutes/AddHours/AddMilliseconds/AddTicks/AddYears/AddDays/AddMonths methods:
DateTime date = DateTime.Now;
TimeSpan initialTimeSpan = new TimeSpan(0, 4, 2);
date = date.AddSeconds(5);
You can use everything in a loop like that:
DateTime initialTime = DateTime.Now;
for (DateTime loopTime = initialTime; loopTime < initialTime.AddMinutes(2); loopTime = loopTime.AddSeconds(15))
{
Console.WriteLine(loopTime);
}
And you will get the following output:
26/09/2015 13:00:33
26/09/2015 13:00:48
26/09/2015 13:01:03
26/09/2015 13:01:18
26/09/2015 13:01:33
26/09/2015 13:01:48
26/09/2015 13:02:03
26/09/2015 13:02:18
To get the output in the format you wanted you can change the printing to the following:
Console.Write(loopTime.Minute + ".");
if (loopTime.Second < 10)
{
Console.Write(0);
}
Console.WriteLine(loopTime.Second);
And you will get this output for the same hours shown above:
0.33
0.48
1.03
1.18
1.33
1.48
2.03
2.18

Synchronizing time in application via JavaScript on iPad

Scenario:
I have a iPad web app which connects to my Exchange server to display the visibility of meeting rooms in Outlook.
The clock must be very accurate (within 5 seconds of the Exchange Server time)
My problem is:
The iPad syncs its time with apples timeserver and there is no way of changing this without jailbreaking the iPad
The iPad clock is not in sync with our server
My current solution:
I have a Clock.aspx page which returns the current time and displays it in the correct div:
var getTime = function () {
$.get('Clock.aspx', function (data) {
$('#txt').html('<h1>' + data + '</h1>');
});
}
However:
This is very inefficient as the call to the server is every 10 seconds (this causes the iPad to crash once every 3/4 days)
What I would like to do:
Is pull the time from Clock.aspx once a hour and increment it using javascript for the rest of the time which will reduce the calls to the server significantly.
Please advise me on the best and most efficient way to do this.
If you have any other suggestions on ways to improve the efficiency I would also love to hear them.
Okay, this isn't perfect but meets my requirements for now - I'd once again appreciate it if more efficient and accurate solutions come up!
var hour = parseInt("<%=DateTime.Now.Hour %>", 10);
var minute = parseInt("<%=DateTime.Now.Minute %>", 10);
var second = parseInt("<%=DateTime.Now.Second %>", 10);
// var x = hour.tostring() +":"+ minute.tostring() +":"+ second.tostring();
// alert(x);
function showTime() {
second++;
if (second > 59) {
second = 0;
minute++;
}
if (minute > 59) {
minute = 0;
hour++;
}
minute = checkTime(minute);
second = checkTime(second);
var clock = hour.toString() + ":" + minute.toString() + ":" + second.toString();
document.getElementById("txt").innerHTML = "<h1>" + clock + "</h1>";
function checkTime(i) {
return (i < 10 ? '0' : '') + i;
}
}
setInterval('showTime()', 1000);
Having used my original answer for a few days I noticed that the sync was out, this script sync's with the server time every hour to re-sync the time accordingly, this means that the accuracy of the clock is very very close with the server. The previous script could lose upto 5 minutes per day. I hope this helps someone!
var serverDate;
function getServerDate() {
serverDate = new Date("<%=DateTime.Now %>");
}
function tick() {
serverDate.setSeconds(serverDate.getSeconds() + 1);
var min = serverDate.getMinutes();
var hour = serverDate.getHours();
var sec = serverDate.getSeconds();
if (min == 30) {
$.get('Clock.aspx?type=2', function (data) {
serverDate = new Date(data.split(">")[1].split("<")[0]);
min = serverDate.getMinutes();
hour = serverDate.getHours();
sec = serverDate.getSeconds();
});
}
if (hour < 10) hour = "0" + hour;
if (min < 10) min = "0" + min;
if (sec < 10) sec = "0" + sec;
document.getElementById("txt").innerHTML = "<h1>" + hour + ":" + min + ":" + sec; + "</h1>";
}
window.onload = function () {
getServerDate();
setInterval("tick()", 1000);
}
Edited to add that clock.aspx is a page which outputs DateTime.Now.ToString()

C# Timer counter in xx.xx.xx format

I have a counter that counts up every 1 second and add 1 to an int.
Question
How can I format my string so the counter would look like this:
00:01:23
Instead of:
123
Things I've tried
Things I've tried so far:
for (int i = 0; i < 1; i++)
{
_Counter += 1;
labelUpTime.Text = _Counter.ToString();
}
My timer's interval is set to: 1000 (so it adds 1 every second).
I did read something about string.Format(""), but I don't know if it is applicable.
Thanks if you can guide me through this :D!
Use a TimeSpan:
_Counter += 1;
labelUpTime.Text = TimeSpan.FromSeconds(_Counter).ToString();
You could make it a TimeSpan (for that's what it is, a span of time), then format that:
labelUpTime.Text = TimeSpan.FromSeconds(_Counter).ToString();
Don't use a counter, and don't rely on the timer firing exactly every second. It won't. Do something like this.
class TimerTest
{
private DateTime _start = DateTime.Now;
private Timer _timer = new Timer(1000);
public TimerTest()
{
// (DateTime.Now - _start) returns a TimeSpan object
// Default TimeSpan.ToString() returns 00:00:00
_timer.Elapsed = (o, e) => labelUpTime.Text = (DateTime.Now - _start).ToString();
}
}
You can adjust the formatting with the TimeSpan.ToString method.
TimeSpan timer = new TimeSpan(0);
and on your interval:
timer += TimeSpan.FromSeconds(1);
Use timespan. To add a second use
mytimespan.Add(new TimespanFromSeconds(1));
Console.WriteLine(mytimespan); //Output in the form of xx:xx:xx
http://www.dotnetperls.com/timespan
it worked well for me
public TimeSpan ElapsedTimeFormatted
{
get
{
if (FinishedOn != null &&
StartedAt != null)
{
TimeSpan durationCount = new TimeSpan();
int hours = 0;
int minutes = 0;
int seconds = 0;
var times = Segments.Select(c => c.ElapsedTimeFormatted).ToList();
foreach (var time in times)
{
TimeSpan timeParse = TimeSpan.Parse(time);
hours = hours + (int)timeParse.Hours;
minutes = minutes + (int)timeParse.Minutes;
seconds = seconds + (int)timeParse.Seconds;
durationCount = new TimeSpan(hours, minutes, seconds);
}
return durationCount;
}
return new TimeSpan();
}
}

Categories

Resources