Adding start delay - javascript

function moveto(coordinates) {
step1 = coordinates[0];
step2 = coordinates[1];
var w = $(document).width();
var h = $(document).height();
$( "#full" )
.animate({left: -(step1 * w)}, 2000 )
.animate({top: -(step2 * h) }, 500 );
}
var randomNum = randomNumbers();
moveto(randomNum);
I need to add start delay of this function and to replay after a certain time

Change this:
var randomNum = randomNumbers();
moveto(randomNum);
To:
function doRandomMove(){
var randomNum = randomNumbers();
moveto(randomNum);
}
setTimeout(function(){
doRandomMove()
setInterval(doRandomMove, 10 * 1000);
}, 1000);
This will first call the change at 1 second, and keeps repeating after 10 seconds after first call.

Try this window.setTimeout("moveto(1,2)", 1000);.
Your function will be called with a delay of 1000ms.

Related

Increment from zero to number in a set time

I am trying to increment from 0 to a number (can be any number from 2000 to 12345600000) within a certain duration (1000 ms, 5000 ms, etc). I have created the following:
http://jsfiddle.net/fmpeyton/c9u2sky8/
var counterElement = $(".lg-number");
var counterTotal = parseInt(counterElement.text()/*.replace(/,/g, "")*/);
var duration = 1000;
var animationInterval = duration/counterTotal;
counterElement.text("0");
var numberIncrementer = setInterval(function(){
var currentCounterNumber = parseInt(counterElement.text()/*.replace(/,/g, "")*/);
if (currentCounterNumber < counterTotal){
currentCounterNumber += Math.ceil(counterTotal/duration);
// convert number back to comma format
// currentCounterNumber = addCommas(currentCounterNumber);
counterElement.text(currentCounterNumber);
} else {
counterElement.text(counterTotal);
clearInterval(numberIncrementer);
}
console.log("run incrementer");
}, animationInterval);
function addCommas(number){
for (var i = number.length - 3; i > 0; i -= 3)
number = number.slice(0, i) + ',' + number.slice(i);
return number;
}
And this somewhat works, but it does not respect the duration. I.e. if you increase the number from 1000 to 1000000000, they both take different amounts of time to reach the destination number.
How can I increment from zero to a number in a specific time frame?
As #Mouser pointed out, the issue is that the animationInterval can't be too small (the actual minimum threshold will vary based on the browser and platform). Instead of varying the interval, vary the increment to the counter:
var counterElement = $(".lg-number");
var counterTotal = parseInt(counterElement.text()/*.replace(/,/g, "")*/);
var duration = 1000;
var animationInterval = 10;
var startTime = Date.now();
counterElement.text("0");
var numberIncrementer = setInterval(function(){
var elapsed = Date.now() - startTime;
var currentCounterNumber = Math.ceil(elapsed / duration * counterTotal);
if (currentCounterNumber < counterTotal){
counterElement.text(currentCounterNumber);
} else {
counterElement.text(counterTotal);
clearInterval(numberIncrementer);
}
console.log("run incrementer");
}, animationInterval);
I played around with your fiddle and found that the delay needs to be higher. At 8ms or 16ms, it is accurate enough to handle a second, but not accurate enough to handle half a second. From experimenting, it seems like a delay of 64ms is small enough to seem like it's incrementing smoothly, but big enough to have an accurate effect.
The difference is that the current number is calculated based on the process rather than directly manipulated.
var counterElement = $(".lg-number");
var counterTotal = parseInt(counterElement.data('total'));
var interval = 0;
var duration = parseInt(counterElement.data('duration'));;
var delay = 64
var numberIncrementer = setInterval(function(){
var currentCounterNumber = 0;
interval += delay;
if (interval <= duration){
var progress = interval / duration;
currentCounterNumber = Math.round(progress * counterTotal);
} else {
currentCounterNumber = counterTotal
clearInterval(numberIncrementer);
}
counterElement.text(currentCounterNumber);
}, delay);
http://jsfiddle.net/c9u2sky8/5/
Also: Javascript timers are not perfectly accurate. But this should be accurate enough for UI use cases.

Javascript function, need to decrement every 30 secs time elapsed

I'm trying to make the this.SPAWN_FREQUENCY decrease by 200 after time elapsed reaches 30 seconds, 1 min, 2 min and so on. Basically levels in the game increasing the amount of enemies to defeat. I've tried a load of code and still can't get anything to work.
Any suggestions where to start?
Sorry if I didn't provide enough detail.
function EnemyManager (timer) {
this.enemies = [];
this.SPEED = -5;
this.SPAWN_FREQUENCY = 1300;
this.spawnTimer = 0;
Do I add 'if' statement?
Use setTimeout
(function () {
var interval = 1000*30;
var SPAWN_FREQUENCY = 1300;
timer = function() {
SPAWN_FREQUENCY = SPAWN_FREQUENCY - 200;
//do the rest
console.log(SPAWN_FREQUENCY);
setTimeout(timer, interval);
interval = interval*2;
};
timer();
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
have you tried something like:
function Manager(){
this.SPAWN_FREQUENCY = 1300;
this.inc();
}
Manager.prototype.inc = function(){
var this_store = this;
setTimeout(function(){
this_store.SPAWN_FREQUENCY -= 200;
this_store.inc();
}, 100);
};
Your function:
var element = this;
var spawninterval = window.setInterval(function(){
element.SPAWN_FREQUENCY -= 200;
},30000);
and when you're done, you can call
window.clearInterval(spawninterval);

Howto run function every few seconds that has return values?

How can I run this every few second , without blocking the rest of the pagefrom loading.
function Create() {
var SomeArray = [];
for ( var i=0; i<=1 ; i ++) {
SomeArray[i] = (Math.random() * 10) + 1;
//alert(arr[0]);
}
return SomeArray;
}
var x = Create();
alert(x[0] + x[1]);
I was trying this var timer = setInterval(Create, 5000); it prevent loading rest of the page.
i want to get new values every few seconds
A basic example would be:
var counter = 0;
var timerRef;
var increment = function() {
counter += 1;
console.log(counter);
timerRef = setTimeout(increment, 1000);
}
setTimeout(increment, 1000);
// clearTimeout(timerRef);
Please avoid document.write refer the screencast for further details.
setInterval() can be configured to repeatedly call any function you designate at whatever time interval you request. But, you can't retrieve a return value from that function. Instead, you need to process the results from within the callback that you pass to setInterval() or call some other function and pass the results you generate inside the callback. This is how asynchronous functions work in JavaScript. I've provided several examples below of your options:
If you just want to generate two random decimal values between 1 and 10 (inclusive) every 5 seconds, you can do that like this:
var interval = setInterval(function() {
var rand1 = (Math.random() * 10) + 1;
var rand2 = (Math.random() * 10) + 1;
// now insert code here to do something with the two random numbers
}, 5000);
If you wanted the random values to be integers (which is more common), then you would do this:
var interval = setInterval(function() {
var rand1 = Math.floor(Math.random() * 10) + 1;
var rand2 = Math.floor(Math.random() * 10) + 1;
// now insert code here to do something with the two random numbers
}, 5000);
If you want to call a function and pass it those two random numbers, you can do this:
function processRandoms(r1, r2) {
// code here to do something with the two random numbers
}
var interval = setInterval(function() {
var rand1 = Math.floor(Math.random() * 10) + 1;
var rand2 = Math.floor(Math.random() * 10) + 1;
processRandoms(rand1, rand2);
}, 5000);
You can then stop the recurring interval at any time with this:
clearInterval(interval);

Get variable and count from 0

Forgive me if this sounds a little confusing ... I am trying to adjust the value of a progress bar based on my randomize variable.
var randomize = Math.round(Math.random() * (3000 - 2000) + 1000);
How do I then get javascript to count from 0 to 'randomize' in seconds, so that I can apply it to my progress bar?
You could do something like this:
var randomize = Math.round(Math.random() * (3000 - 2000) + 1000);
var counter = 0;
var timer = setInterval( function(){
if ( counter <= randomize ){
// update progress bar
counter += 1;
}else{
clearInterval( timer );
}
}, 1000 );
Basically what I'm doing here is setting up a function to be called every second ( 1000 = 1 second in JavaScript). The timer will check if the counter variable has reached the value of randomize and if not, it will increment it's value by one.
Once counter is equal to randomize, the timer will be cleared.
References -
setInterval()
clearInterval()
var seconds = 0;
var timer = setInterval(function() {
seconds = seconds + 1;
if (seconds == randomize) {
clearInterval(timer);
}
}, 1000);

Increment integer by 1; every 1 second

My aim is to create identify a piece of code that increments a number by 1, every 1 second:
We shall call our base number indexVariable, I then want to: indexVariable = indexVariable + 1 every 1 second; until my indexVariable has reached 360 - then I wish it to reset to 1 and carry out the loop again.
How would this be possible in Javascript? - if it makes a difference I am using the Raphael framework.
I have carried out research of JavaScript timing events and the Raphael delay function - but these do not seem to be the answer - can anyone assist?
You can use setInterval() for that reason.
var i = 1;
var interval = setInterval( increment, 1000);
function increment(){
i = i % 360 + 1;
}
edit: the code for your your followup-question:
var interval = setInterval( rotate, 1000);
function rotate(){
percentArrow.rotate(1,150,150);
}
I'm not entirely sure, how your rotate works, but you may have to store the degrees in a var and increment those var too like in the example above.
var indexVariable = 0;
setInterval(function () {
indexVariable = ++indexVariable % 360 + 1; // SET { 1-360 }
}, 1000);
Try:
var indexVariable = 0;
setInterval(
function () {
indexVariable = (indexVariable + 1) % 361;
}, 1000}

Categories

Resources