I am trying to use JavaScripts WebWorkers and setTimeout to have a asynchronous Timeout on a ChromeCast Application.
This is used inside of jQuery, but the call to the asynch javascript file is outside of jQuery.
This is the minimal sample (without jquery and working standalone):
index html:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<script>
function func(){
console.log("start");
var worker = new Worker('timer.js'); //External script
worker.onmessage = function(event) { //Method called by external script
console.log("10s later");
};
}
</script>
<body onload="func()">
</body>
</html>
timer.js:
setTimeout(continueExecution, 10000) //wait ten seconds before continuing
function continueExecution()
{
postMessage(null);
}
the callback works inside the chromecast and jQuery, but is executed instantaneously without the delay of 10 seconds.
Does anyone know how the chromecast handles timeouts ?
setTimeout does work on Chromecast, you can check out our reference receiver which uses that method in multiple places.
Related
What I want to do is use JavaScript (or some other client-side way) to listen for events occurring outside the web page without server-side help. It might look like this:
// tester.js
cses = new ClientSideEventSource("JSEventSource.js");
cses.onmessage = function(event){
// do something
}
// JSEventSource.js
CSES_return("CSES has been run!");
// note how this is client-side
The problem here is that this is all imaginary because those functions (sadly) don't exist. AJAX calls to JS files don't work. Here is an example of it's usage:
function getNotifications()
{
var cses = new ClientSideEventSource("JSEventSource.js");
cses.onmessage = function(event){alert(event.data)}
}
function sendNotification()
{
CSES_return("You have got a notification!");
// this does not give an error even if this is not used in CSES mode
// which is started with: new ClientSideEventSource("jsfile.js");
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Test</title>
<meta charset="UTF-8"/>
</head>
<body>
<button onclick="getNotifications()">Get Notifications</button>
<button onclick="sendNotification()">Send Notification</button>
</body>
</html>
<!-- You will get errors because ClientSideEventSource and CSES_return do not exist -->
That is basically a messaging system (with a certain message) that doesn't use any Server-Side code. Is there anything to replicate this?
I just try to test a very basic program in javascript but on my computer it does not work. It works on other computer but not mine. I'm launching it on chrome which has javascript activated. There is my code:
index.html
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>p5.js</title>
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.js">
</script>
<script src="script.js" type="application/javascript;version=1.7"></script>
</head>
<body>
</body>
</html>
script.js
function setup() {
createCanvas(400,400);
background(0);
var x = random(0,200);
rect(x,x,(200-x)*2,(200-x)*2);
}
function draw() {
}
In my folder I have also an asset folder which is empty and my style.css is empty. With this code I am supposed to have a black square on my screen (the canvas) but there is nothing, and when I check the console on chrome nothing is written. Moreover, the first time I launched index.html a file named debug.log appears:
debug.log
[0126/184004.266:ERROR:settings.cc(263)] Settings version is not 1
Why does this script work on other computer but not mine ?
Thanks for helping.
All of your audio your files listed in the JavaScript code MUST be named as HTTPS, not HTTP. And obviously, that means the website(s) you are linking to (including yours) must be secure. That is, you need to have your security certificates, and make sure they are activated. It's a security issue with Chrome. I hope that helps. = -)
You need to call your function:
index.html
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>p5.js</title>
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.js"></script>
<script src="script.js" type="application/javascript"</script>
</head>
<body>
</body>
</html>
script.js
function setup() {
createCanvas(400,400);
background(0);
var x = random(0,200);
rect(x,x,(200-x)*2,(200-x)*2);
}
function draw() {
}
setup(); // that is a function call
I tested this on Firefox and Chrome and it works. Javascript is interpreted by your browser, it has nothing to do with your computer. If the exact setup above doesn't work for you then check here. If JS is enabled and it still doesn't work then try removing the p5.js script. If that still doesn't fix it then reinstall Chrome (or even better switch to Firefox)
The accepted answer would be correct if you were not using P5.js. But since you are, you should not call the setup() function yourself! Instead, you need to let P5.js do that for you automatically. It might work with this simple example, but you'll have other problems with e.g. draw() not being called 60 times per second. If setup() and draw() are not being called, that means you're not loading the library correctly.
You need to check your developer tools for any errors, both in the JavaScript console and in the network tab.
My guess is that you're accessing your page as a file:// URL, which can have problems. You need to run a local server and access your files that way instead.
I'm using an event which is called after the complete site is loaded. So I use onload() for that.
Is there any way to call my function before or during the site is loaded?
I would be very grateful!
Thank You!
<html>
<head>
<title>My title</title>
<script>
var x = 2;
function timesTwo(num){
return num * 2;
}
console.log(timesTwo(x));
</script>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
That way your JavaScript code is being interpreted and executed before the websites Body is being rendered. Keep in mind, that if you use that approach and are executing some JS that takes up some time, the websites display time will be delayed by same amount.
If you want to call something as early as possible, put it in a script tag at the beginning of the <head> element. However, you can't guarantee any libraries are loaded or any of the page has been loaded yet. If you want to do something as soon as possible, and are using jquery, use $(function() { yourFunctionHere() }). If you aren't using jquery, use the DOMContentLoaded event
You may listen on the 'readystate' event to do something before the 'DOMContent' event. And do not forget to put the snippet in head tag.
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', function () {
console.log('DOM content loaded');
};
document.addEventListener('readystatechange', function () {
console.log('[Ready state is]', document.readystate);
if (document.readystate != 'complete') {
console.log('You can do something here');
}
};
</script>
<body>
</body>
</html>
The output can be:
[Ready state is] interactive
You can do something here
DOM content loaded
[Ready state is] complete
Hope it helps.
I know that when you want to invoke a JavaScript function inside a HTML body section you can do it by putting <script> someFunction(); </script> inside your body tag, here is an example, I have HTML like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript"
src="/Script.js"></script>
</head>
<body>
<script>
showAlert();
</script>
</body>
</html>
And the javascript file like this:
function showAlert(){
alert("This is an alert!");
}
This works fine but if I put the JavaScript file reference at the end of the body like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<script>
showAlert();
</script>
<script type="text/javascript"
src="/Script.js"></script>
</body>
</html>
the function showAlert() is no longer being invoked. Can you please answer these 2 questions:
Why is showAlert() not invoked in the second scenario?
How (if possible) to invoke a function from a JavaScript file when
it is referenced in the end of the body?
The reason why I'm asking is because I know that it is a good practice to refer your JavaScript files in the end of the body instead of the head, so that the page will be rendered first before loading all the JavaScript code.
1) The scripts are loaded linearly. Since the script has not yet been loaded, the function is undefined. (This is in contrast to function hoisting within a script.)
2) Simply wait till the page loads.
window.onload = function(){
showAlert();
}
(Simply doing window.onload = showAlert won't work because of reason #1. Here you delay evaluation until such time that the function will exist.)
Assuming you want to run showAlert() immediately when the page has loaded, try adding an onload() event handler to call showAlert rather than just calling it as the script loads. This can be done a few ways:
<body onload="showAlert();">
or define the window onload event programatically where your current function all is made in the html
window.onload = new function() {showAlert();}
or (and I think this is the preferred way because it won't cancel out other event handlers bound to the onload event)
window.addEventListener("load", showAlert);
By default, scripts run sequentially. Your code doesn't work because showAlert() runs before loading Script.js, so at that point the function showAlert is not defined yet.
To make it work, you must delay the showAlert call.
The load event has already been mentioned in other answers, but it will wait for all resources (like images) to load. So listening to the DOMContentLoad event is usually better, the function will be called sooner.
<script>
document.addEventListener('DOMContentLoaded', function() {
showAlert();
});
</script>
<script src="data:text/javascript,
function showAlert() {
console.log('Hello!')
}
"></script>
The reason for your script isn't working is the way how a webpage is parsed..From top to bottom..Here is some link (would help to know why script added at bottom).
1) in your First case the browser loaded script when it parsed the page and when you called it in body it was available so it got invoked.
2) in Second scenario (My be typo) You have placed the call to function before loading the script that contain your function. so during page parsing browser wont find it and continue to next line where script containing function is loaded which has no effect for now as it already parsed the call.
If you still want to follow the second scenario you have to trigger the function call (after ensuring all resources being loaded ie Your script).
so you can use window.load=<your function call> or in case of jQuery place it inside
$(document).ready(function(){
//call here
});
Javascript processes in the order given. You are trying to call showAlert before showAlert have been defined. Change to:
<body>
<script type="text/javascript"
src="/Script.js">
</script>
<script>
showAlert();
</script>
</body>
and all should work as intended.
Here's the situation:
Client wants a looping SWF file to pause for two seconds before it begins playing all over again (it's a nice build animation on a logo, but the logo doesn't stay on the screen for very long because the movie repeats so users can't see the logo for long. This is irrelevant, but good back story.)
They provided me with a SWF file, but not FLA. When I asked for the FLA I was told the hard drive that contained the FLA crashed and it cannot be retrieved. So, that is pretty much a dead-end.
Before I go and try to de-compile the SWF and all that fun stuff, I wanted to know if there was any way that this could be done with HTML and Javascript. That is:
Have the SWF loop
Pause the movie for two seconds before it restarts
What do you think?
This isn't easily possible with javascript, but it is very easy if you load the swf into another swf. You then have access to the main timeline of the original swf and you'd be able to control it. If you want to control a movie called targetMovie.swf you can do something like this:
var loader:Loader = new Loader();
loader.load(new URLRequest("targetMovie.swf"));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
addChild(loader);
var logoMovie:MovieClip;
function onComplete(evt:Event):void{
logoMovie = MovieClip(loader.content);
// call pauseMovie at end of timeline
logoMovie.addFrameScript(logoMovie.totalFrames-1, pauseMovie);
}
function pauseMovie():void{
logoMovie.stop();
// delay for two seconds;
setTimeout(function(){
logoMovie.play();
}, 2000);
}
You could simulate this entirely in javascript with swfObject. You would need to time how long the animation is, add two seconds, and make that the time before the script restarts. heres a working example with the homestarrunner intro:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://swfobject.googlecode.com/svn-history/r409/trunk/swfobject/swfobject.js"></script>
<script type="text/javascript">
$(document).ready(function(){
startSwf()
})
var restartTime = 24500 //in milliseconds
function stopSwf(){
swfobject.removeSWF("swfLoop");
startSwf();
}
function startSwf() {
$("body").append("<div id='swfLoop'></div>");
swfobject.createSWF({data:"http://homestarrunner.com/newintro.swf", width:400, height:300}, null, "swfLoop");
setTimeout('stopSwf()', restartTime);
}
</script>
</head>
<body></body>
</html>
plug that in here: http://htmledit.squarefree.com/
Try this http://www.permadi.com/tutorial/flashjscommand/