loading a new page after a short pause/delay using javascript - javascript

Am very new to javascript and am trying to simulate a simple animation where I want to load a html page which has the canvas that has some figures and then wait for 3 seconds and load another set of figures on top of the existing ones for it to look like a simuation. I have tried using the setTimeout but that just doesn't kick in after all the iterations are over. Was wondering if there is anything special that needs to be taken into account with canvas?
Thanks!

You can use the following function of javascript
setTimeout(
function()
{
//do something special
}, 3000);
In this 3000 is 3000 milliseconds , so can increase or decrease it.

You can make a variable displayRects and do in draw function if (displayRects) {
//draw rects
}
And before on document load do
setTimeout(function(){displayRects = true},3000);

Related

Javascript update functions

I'm getting into game developing online. I am trying to make an online FPS game, and I've only gotten to the point where I need to update my character. I am trying to keep my code simple, using only a draw and update function. When the html loads, I execute both: (Is this necessary?)
<body onload='DRAW(); UPDATE();'>
The draw function draws the player to the screen, and the update is supposed to check for a keypress to move the character. I am trying to make the script update using this:
function UPDATE()
{
update = setInterval(UPDATE, 60);
}
and to my knowledge, it is working fine because when I try and edit code in my online IDE (c9.io) which I use to test the site, it freezes when the site is running. I am also calling eventListeners in the draw function. (Is this proper if I want to test for a key down every frame?)
function DRAW()
{
window.addEventListener('keydown', function (e) {
keys.keys = (keys.keys || []);
keys.keys[e.keyCode] = true;
});
window.addEventListener('keyup', function (e){
keys.keys[e.keyCode] = false;
});
}
My questions are:
Is there an easier way to make a script update every frame?
Is there a JavaScript addon (like Three.js) I can use to make
developing this easier on myself?
Any knowledge is greatly appreciated.
This makes everything crash:
function UPDATE()
{
update = setInterval(UPDATE, 60);
}
You are recursively creating a new interval every 60ms; the first time you call UPDATE, you create an interval that creates a new interval every 60ms. All newly create intervals do the same. Don't really know what you actually want to do here.
I am also calling eventListeners in the draw function. (Is this proper
if I want to test for a key down every frame?)
It's fine to create eventlisteners in the draw function, provided you only call this function once. Which I guess you don't. Each time you call DRAW() a new set of eventlisteners will be added, and you really don't want that.
What you need is a form of game loop. Explaining how to create an FPS game is a bit more than I can do, but you can start by looking at this article Anatomy of a video game

How do I slow down the execution of a jquery click function?

I use a simple jquery command in the Google Chrome console to manage my site. Basically, I have to approve a number of new requests every day, so I use:
$('.approve').click();
where 'approve' is the class name of the button that needs to get clicked. This saves me hours. However, this crashes my browser every time, and sometimes doesn't work, mainly because of the resource taxing it put on my laptop. I was looking for a way to slow down the actions of the function. I tried...
$('.approve').click().delay(1000);
to try and slow it down by 1 second between button clicks. This didn't seem to work (it ran without errors but I don't think it slowed down the clicking.
Any ideas?
Edit:
Someone pointed out that this may be a duplicate of another question. The reason it isn't is that the other top answer focuses on using JS to define a function that uses setTimeout(), where I am looking for a native jquery method of doing it. I understand jquery is written in JS, but because I'm using it in a command console, I don't have the luxury of multiple lines of coding space.
Can anyone also tell me why the above function wouldn't work? It seems like it should, based on my research.
Thank you in advance.
Wait 1 second between each click:
You will need to iterate over each .approve-button, then trigger the click event for each button with a second in between: (setTimeout)
$('.approve').each(function(index) {
var $approve = $(this);
setTimeout(function() {
// Simulation click event
$approve.trigger('click');
// 0, 1, 2, 3, ... times 1000 to bring delay to miliseconds
}, index * 1000);
});
One liner (For IE9+):
$(".approve").each(function(c){setTimeout(function(c){c.click()},1e3*c,$(this))});
One liner:
$(".approve").each(function(e){var i=$(this);setTimeout(function(){i.click()},1e3*e)});
You can add a delay on the function click like so
$(".approve").click(function(){
setTimeout(function(){
// Do something
}, 1000);
});
If you want to exectue your function once, use setTimeout()
$(".approve").click(function(){
setTimeout(function(){
}, 1000);
});
If you want to exectue it every second, use setInterval()
when click you have to run a function that will execute setTimeout function
$('.approve').click(function(){
setTimeout(function(){
// here some code u want to execute after 5 sec //
}, 5000);
});

Running multiple jquery functions together

I know this question has been asked a lot of times, and I have seen the solutions to them on SO as well as other forums. Most of the times the solution suggested is to use Web Workers.
A game I'm developing requires me to run multiple functions at the same time. One of them is an on click function and other is a setInterval.
My approach at doing this can be seen here in this JSFiddle. (keep clicking in gray area to make player jump).
The whole idea is to continuously spawn those blue obstacles after an interval of 1000ms.
In my earlier approach the obstacles would spawn only when I click to make player jump, otherwise they wouldn't as expected.
How can I run such two functions side by side in order to achieve
the aim of spawning obstacles while also making player jump.
Secondly, what would be the best approach to carry out this process
in view of game development i.e attaining a certain level of
efficiency so that the animations are not affected.
Here is the HTML and Javascript code I've been working on:
<div class="container">
<div class="player"></div>
<div class="obstacle-container">
<div class="obstacle"></div>
</div>
</div>
$.fn.animator = function () {
var hit_list, done = false;
$(".container").click(function () {
if (!done) {
$(".obstacle").stop().animate({
left: "-=105%"
}, 10000, "linear");
$(".player").stop().animate({
bottom: "+=100px"
}, {
duration: 300,
complete: function () {
$(".player").animate({
bottom: "0"
}, 800);
},
step: function () {
//Test for collision
hit_list = $(".player").collision(".obstacle");
if (hit_list.length !== 0) {
$(function () {
if (!done) {
$(".container").append("Game Over!");
return false;
}
});
done = true;
}
}
});
}
});
};
$(function () {
$('.container').animator();
});
var interval = null;
$(".obstacle-container").obstacle_generator();
$.fn.obstacle_generator = function () {
interval = setInterval(function () {
$(".obstacle-container").append('<div class="obstacle"></div>');
}, 1000);
};
The generic concept you want to investigate is known as a game loop.
Almost every game will be built using some variant of this system:
Initialise game
Loop:
Check for user input
Update any actors
Draw the scene
Wait until it's time to repeat
A game running at 60 frames per second would perform this loop 60 times per second, or about once every 16ms.
Compared to your original question, you wouldn't need to be running multiple execution threads (running multiple functions together) to achieve this.
You are, in a way, already using a similar loop. jQuery maintains its own loop for updating animations. Where you are checking for collisions as part of your animation step, this is the sort of thing you would do in a hypothetical Player.update() method. You want to move this code out of jQuery, and in to a loop that you control.
Since you're running in a browser, the generic game loop becomes a bit more simple:
Check for user input - this can still be handled by event handlers, jQuery or not. Rather than directly changing properties like CSS position, though, they should act upon the state of the game object. For example, by changing the velocity of a Player object.
Update any actors - the important part of your loop. You should check how many milliseconds have passed since you last looped, since the browser doesn't guarantee that your code will be run exactly, or at least, 60 times per second. You should then loop through all of your game objects and update them all. In your Player.update() method, you would want to move it according to its velocity and the time passed, for example.
Draw the scene - if you're using DOM elements, then the browser handles drawing for you, of course. If you were using a <canvas> element, then you would do drawing yourself as part of the loop here.
Wait until it's time to repeat - this will be up to the browser to do for you, as part of normal setInterval/setTimeout behavior.
A simple game loop in JavaScript can look like this:
var gameObjects = [];
// Initialise game, create player objects etc, add them to the array
var gameLoop = function() {
// Loop through gameObjects, and call their respective update methods
};
setInterval(gameLoop, 16); // Try to run the loop 60 times per second.
In a complex game, you wouldn't have just a basic array to hold all game objects, this is just an basic example.

How to interupt javascript to flush events

I have a function running on document load that copies the contents of a select object to other select boxes (to conserve network bandwidth).
The function is taking a few seconds to complete, so I wanted to mask the main div (to give the user the idea that something is happening).
Unfortunately, the mask is not showing up until after the function completes:
// I want the mask to show immediately here, but never gets shown
$('#unassignedPunchResults').mask('Getting results');
$('.employeeList').each(function (i) {
// this is freezing the browser for a few seconds, the masking is not showing
$('#employeeList option').clone().appendTo(this);
});
$('#unassignedPunchResults').unmask();
How can I interrupt the javascript after the mask() call to flush that event and continue, so the user can see the mask while the longer processing (the each()) processes?
Put the rest of the code in a setTimeout(function() { ... }, 0) call.
I've been thinking a while about this.
The first solution is to use the settimeout function.
However it could be a little 'dirty' because you add an arbitrary delay. A more proper logic would be to execute the $('.employeeList').each(function (i)... function after the mask function has benne executed and rendered.
Jquery allows us to do that with the deferred functions like then which xecutes after a deferred condition has been satisfied.
So try with:
// I want the mask to show immediately here, but never gets shown
$('#unassignedPunchResults').mask('Getting results').then(function(){
$('.employeeList').each(function (i) {
// this is freezing the browser for a few seconds, the masking is not showing
$('#employeeList option').clone().appendTo(this);
});
});
In general, using settimeout with an arbitrary number of ms is a solution which works for simple cases, but if you have multiple settimouts in a complex code then you could have synchronizaton problems.
or use a worker, but then you need to discard msie < 10
or break up your calculations in segments that run for less than 500 ms and use setinterval to sread the loading over 5 seconds.
google simulate threading in javascript for code examples.

Sequencing Events in Javascript

I am trying to make a simple hidden object game using javascript. When the user finds and clicks an image, I want 3 things to happen in the following order; a sound plays, the image size increases, and the image goes invisible. The problem I am running into is getting the 3 events to happen sequentially, not concurrent. Right now, seems that all three events happen all at the same time.
I've tried using setTimeout(), and while that does create a delay, it still runs all functions at the same time, even if each function is nested in setTimeout.
Example: (all this does is waits 1.5 sec then plays the sound and makes the image invisible):
function FindIt(image, id){
var t = setTimeout('sound()',10);
var b = setTimeout('bigger(' + image + ')',30);
var h = setTimeout('hide(' + image + ')',1500);
}
Below are the functions I am currently using and the actual results are: click the image, nothing happens for 2 seconds, then the sound plays and the image goes invisible.
function FindIt(image, id){
sound();
bigger(image);
hide(image);
}
function sound(){
document.getElementById("sound_element").innerHTML= "<embed src='chime.wav' hidden=true autostart=true loop=false>";
}
function bigger(image){
var img = document.getElementById(image);
img.style.width = 112;
img.style.height = 112;
}
function hide(id){
var ms = 2000;
ms += new Date().getTime();
while (new Date() < ms){} //Create a 2 second delay
var img = document.getElementById(id);
img.style.visibility='hidden';
}
Any guidance would be greatly appreciated!
To trigger things sequentially, you need to execute the second item some amount of time after the first one completes, execute the third item some amount of time after the second one completes, etc...
Only your sound() function actually takes some time, so I'd suggest the following:
function FindIt(image, id){
sound();
// set timer to start next action a certain time after the sound starts
setTimeout(function() {
bigger(image);
// set timer to start next action a certain time after making the image bigger
setTimeout (function() {
hide(image);
}, 1000); // set this time for how long you want to wait after bigger, before hide
}, 1000); // set the time here for how long you want to wait after starting the sound before making it bigger
}
FYI, the animation capabilities in libraries like jQuery or YUI make this sort of thing a lot easier.
Also, please don't use this kind of construct in your JS:
while (new Date() < ms){}
That locks up the browser for that delay and is very unfriendly to the viewer. Use setTimeout to create a delay.
For reference, using the animation libraries in jQuery, the jQuery code to handle a click on the object and then animate it over a 2 second period to a larger size, delay for 1 second, then slideup to disappear is as follows:
$("#rect").click(function() {
$(this).animate({height: 200, width: 400}, 2000).delay(1000).slideUp();
});
jQuery manages an animation queue and handles setting all the timers and doing all the sequencing and animation for you. It's a lot, lot easier to program and gives a very nice result.
You can see it work and play with it here: http://jsfiddle.net/kC4Mz/.
why don't use "event" approach. like onTaskDone();
function task1(arg, onTask1Done){
console.log(arg);
if(onTask1Done)onTask1Done();
}
task1("working", function(){console.log("task2");});
The Frame.js library is designed to elegantly handle situations like this:
function FindIt(image, id){
Frame(10, function(next) { sound(); next(); });
Frame(30, function(next) { bigger(image); next(); });
Frame(1500, function(next) { hide(image); next(); });
Frame.start();
}
Frame.js offers many advantages over using standard timeouts, especially if you are doing a lot of this kind of thing, which for a game, you likely are.
https://github.com/bishopZ/Frame.js

Categories

Resources