Synchronization value of the variable in JavaScript - javascript

I would like to show on my website some data, which should be changing every 30 seconds.
However, when someone open my website and there is 18 seconds left to change, JS should wait 18 seconds, change the data and then set setInterval().
I tried this code:
var howmany = 1502; //seconds
var rest = howmany % 30
if(rest > 1) {
window.setTimeout(function() {
upgradeProducts();
setInterval("upgradeProducts()", 15000);
}, rest*1000);
}
else {
setInterval("upgradeProducts()", 15000);
}
but it is not working. Where did I make mistake?

You need to take reference to current time, which would be a cross-reference between every user of your website.
In your case, the starting point is the same for everyone (30 % of 1500 seconds).

Related

PHP timer that resets after x seconds

I trying to implement a timer to my website, as I want the timer to be the same for anyone entering, even if the timezones is different, I believe PHP works better than javascript, using time() maybe?
I'll explain.
I want my timer to start at 50 seconds and go to 0 seconds, once it hits 0 the timer should reset. So, as mentioned, when I reload the page the timer should not reset. If the timer is e.g 34, and I reload the page, the timer should not reset back to 50, it should keep going, so if it takes 2 seconds to reload the page, the timer should be 32 in this case.
The timer should also be the same of everyone, if my friend in Russia is seeing 44 seconds, then my friend in Spain should also see 44 seconds.
I don't have an example code as I simply don't know how to do it.
I know this is probably not the best, maybe even the worst method but it works.
var count = 50;
setInterval(function(){
document.getElementById('counter').innerHTML = count;
count--;
if (count < 0){
count = 50;
}
}, 1000);
<h1 id="counter"></h1>

JavaScript/JQuery countdown timer with multiple interval settings?

I want to countdown from a number, let's say 100. But I don't want the countdown to be obvious such as in seconds. I would like 3 intervals like below and if they could be random, that would be even better. Each number change, I want to setup a cookie that holds the new value.
2 seconds
8 seconds
14 seconds
So it works like so:
User lands on page, Sees the number 100, then either 2,8 or 14 seconds later, the 100 decrements down to 99 and so on until it hits 0. Say the user sees 2 intervals and is left with 98, that value should be set in the cookie, so when they visit the page again, the don't see 100, but the new value.
Hard, any plugins to help me?
You could use the $.doTimeout() jQuery Plugin along with the $.cookie() jQuery plugin together like this:
HTML:
<div id="timer"></div>
JavaScript:
var timer = ($.cookie('timer_cookie') != '') ? $.cookie('timer_cookie') : 100; // Current Timer
var intervals = [2000,8000,14000]; // Available Timer Intervals
var rand = Math.floor(Math.random()*intervals.length) // Random Number for Choosing Intervals
$('#timer').text(timer);
$.doTimeout('timer_id', intervals[rand], function(){
timer = parseInt($('#timer').text()) - 1;
$('#timer').text(timer);
$.cookie('timer_cookie', timer);
return true;
});
This is untested but should do the trick; hope it helps!

Add a countdown in my scoring script (javascript/jquery)

I have the following script in a js file:
// Ad score
var score = 0;
//$('#score').text(score);
function foundMatchingBlocks(event, params) {
params.elements.remove();
score += 100;
$('#score').text(score);
};
Now on each matching, 100 points are added to var score. This all works. Now I want to extend this a bit. As soon as the page loads I want to start a countdown to reduce the number of points (starting with 100) with 1 point a second for 60 seconds. So the minimum number of points a user can get is 40. When someone gets the points, the counter should reset and countdown again.
Example:
Page loads (timer starts from 100)
User has a match after 10 seconds (+90 points are added)
Counter resets and countdown from 100 again
User found a match after 35 sec (+65 points are added)
etc etc
Problem is, I have no idea how to do this :( Hope someone can help me with this.
The above is fixed, thanks all for helping!!!
The big picture is, you'll need to become pretty familiar with timeouts and intervals in javascript. This is the reference page I keep going back to when I need to refresh my memory: http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
For your specific task, you'll probably want to use an Interval that triggers every 1000 milliseconds to calculate the second-by-second point reduction, and a separate Timeout for failure that resets every time the user completes their challenge.
Here are a few tips for working with timeouts and intervals that usually lead to followup questions:
When you set a timeout, always capture the return value (I think it's basically a random integer). Save it to some global var for convenience.
var failureTimer; // global var high up in your scope
failureTimer = setTimeout ( "gameOver()", 100000 ); // 100 seconds * 1000ms
Then in whichever method gets called when the player completes their challenge, you call this:
clearTimeout (failureTimer); // resets the timer and gives them another 100 seconds
failureTimer = setTimeout ( "gameOver()", 100000 ); // yes call this again, to start the 100 sec countdown all over again.
The second pain point you're likely to encounter when working with Timeouts and Intervals is how to pass parameters to the functions like gameOver() in my example above. You have to use anonymous functions, as described here:
Pass parameters in setInterval function
For more on anonymous functions, this is a good overview:
http://helephant.com/2008/08/23/javascript-anonymous-functions/
Good luck with your project! Let me know if you have any questions.
Here's some code without the use of timers. Call startCountdown() every time you want to re-initialize the count-down. Call getAvailableScore() when you want to fetch the current available score. You will have to decide what to do when the available score goes to zero.
var beginCountDownTime;
function startCountdown() {
beginCountDownTime = new Date();
}
function getAvailableScore {
var now = new Date();
var delta = (now.getTime() - beginCountDownTime.getTime()) * 1000; // time elapsed in seconds
var points = 100 - (delta / 60);
return(Math.round(Math.max(points, 0))); // return integer result >= 0
}
Maybe something like:
// Ad score
var score = 0;
var pointsAvailable = 100;
//$('#score').text(score);
function foundMatchingBlocks(event, params) {
params.elements.remove();
score += pointsAvailable;
$('#score').text(score);
pointsAvailable = 100;
};
$(document).ready(function() {doTimer();});
function doTimer() {
setTimeout('reducePoints()',1000);
}
function reducePoints() {
if(pointsAvailable>40) {
pointsAvailable--;
}
doTimer();
}

Canvas scroll animation not working correctly

I'm building a gantt chart style timeline using html canvas element.
I am currently attempting to add the functionality which allows the user to click a next/prev button to have the gantt chart scroll to display earlier or later times.
The way I am doing this is to have a span.adjustTime where the id holds a value in seconds for the time to be adjusted (eg 86400 for one day).
I am trying to animate the scrolling so it looks like a scroll, rather than jumping ahead by one day.
I have a small problem in my timing calculation, but the script below is not animating, but rather jumping directly to the final time.
I do have the draw function running on a separate setInterval which updates every second, so I'm hoping it isn't an issue of conflicting timers on the same function on the same element and data.
jQuery('span.adjustTime').click(function() {
var adjustBy = parseInt(jQuery(this).attr('id').replace('a', ''));
var data = jQuery('img#logo').data();
for(var m = 1; m >= 30; m++) {
gantt.startUnixTime = gantt.startUnixTime + (adjustBy * (m * 0.001));
var moveTimer = setTimeout(function() {
draw(document.getElementById('gantt'), data, gantt);
}, 1000);
if (m == 30) {
clearTimeout(moveTimer);
}
}
});
In the for loop you are calling setTimeout 30 times, each time with the same timeout value of 1000. So after 1000 milliseconds 30 scheduled functions will execute at almost the same time. I suppose this is not what you intended. If you wanted an animation of 30 frames over 1000 milliseconds, the setTimeout should look something like:
setTimeout(function() { ... }, 1000 / 30 * m)
Also note that all 30 scheduled functions will see the same gantt.startUnixTime value, since the same object (gantt) is passed to all of them, and when they execute, the for loop has finished already long ago.

How can I make a javascript/jQuery countdown that is only visible after X minutes?

After the users have been inactive for X minutes, I need to display the number of minutes left till the session times out in ASP.NET.
For e.g. after 5 minutes, they will see 'You have been inactive for 5 minutes. You will be logged off after another 10 minutes'. Each minute after that, the message will be updated.
I found a jQuery plugin called 'jQuery Countdown', but how can I make it visible only after X minutes have passed?
When the page loads, I will use RegisterStartupScript while passing Session.Timeout as a parameter to this function.
Thanks for your help.
You could fade it in after 5 minutes using .delay() like this:
$("#timer").delay(299600).fadeIn(function() { // 5 * 60 * 1000 - 400ms for fade
$(this).countdown({ ... countdown options ... });
});
This is basically just doing a setTimeout() behind the scenes on the queue, just a short/simple way of doing the same. That being set, setTimeout(showFunc, 300000) will do the job just fine.
you can use a regular javascript setTimeout function
and set it to 5 minutes...
and put a function there that will make your countdown visible
var interval = setInterval(displayInactiveMessage, 300000);
300000 = 5 minutes in milliseconds.
Then clearInterval(interval) to stop it from running every 5 minutes.
Yo can you the same mechanism for you 1 minute updates - just don't clear it.

Categories

Resources