Run script once per browser session, but freeze script at end - javascript

I have a site in development here and I'm happy with the intro. However, I need this script to run once oer browser session, and then to remain in its final state for the remainder of the session. Is this possible, or should I rearrange something. I'm pretty new to this and need a bit of help! My intro script is below:
var words = ['websites', 'animation', 'branding', 'illustration'];
var i = 0;
var final = "thirdrail";
var splash = setInterval(function() {
$("#word").hide().html(words[i++]).fadeIn(500);
if (i == words.length + 1) {
$("#word").html(final);
clearInterval(splash);
var time = setTimeout(function() {
$(".overlay").addClass("level");
$("#word").addClass("before");
$(".logo").addClass("final");
$("#static").html('<img src="symbol.svg"/>');
$("nav").css('right', '-20px');
$(".icon").css('right', '5%');
}, 2000);
}
}, 1000);

Complete example, if you need it
var final = "thirdrail";
function startSplash() {
var words = ['websites', 'animation', 'branding', 'illustration'];
var i = 0;
var splash = setInterval(function() {
$("#word").hide().html(words[i++]).fadeIn(500);
if (i == words.length + 1) {
$("#word").html(final);
clearInterval(splash);
var time = setTimeout(function() {
endSplash();
localStorage.setItem("splashed", true);
}, 2000);
}
}, 1000);
}
function endSplash() {
$("#word").html(final);
$(".overlay").addClass("level");
$("#word").addClass("before");
$(".logo").addClass("final");
$("#static").html('<img src="symbol.svg"/>');
$("nav").css('right', '-20px');
$(".icon").css('right', '5%');
}
if(!sessionStorage.getItem("splashed")){
startSplash();
} else {
endSplash();
}

You could use cookies, or localStorage:
if(localStorage.getItem("intro"){
//go to normal page
}else{
localStorage.setItem("intro",true);
//show intro
}
Like Sam said while i wrote this...

Related

jQuery Title Change with array elements

I'm trying to get this code to change the page title based on array elements. But there is something wrong with this code. I need the page title show the entire array only when the browser tab is inactive. When the browser tab is active show the real page title. This is the code that I got so far
Here is a fiddle: https://jsfiddle.net/hgmvqasn/2/
/*
*
Title Change Plugin, adapted
*
*/
window.onload = function() {
var pageTitle = document.title;
var appeal = ["Hello! ♥","Welcome Back!", "Are you sure?"];
var blinkEvent = null;
document.addEventListener('visibilitychange', function(e){
var isPageActive = document.visibilityState;
console.log(isPageActive);
if (isPageActive == "hidden") {
blinkEvent;
} else {
document.title = pageTitle;
clearInterval(blinkEvent);
}
})
blinkEvent = setInterval(function() {
function blink(){
for (i = 0; i < appeal.length; i++){
document.title = appeal[i];
console.log(appeal[i]);
}
// To make instant page title change (no wait the interval)
document.title = appeal[1];
}
}, 1900);
};
The code above does not display all items in the array or displays them in wrong way. In addition the interval is not interrupted when the tab becomes active again.Can someone help me?
You shouldn't have the for loop. You just want one timer, not a timer for each string in the appeal array. That timer should increment the index and display the next title.
window.onload = function() {
var pageTitle = document.title;
var appeal = ["Hello! ♥", "Welcome Back!", "Are you sure?"];
var appeal_index = 0;
var blinkEvent = null;
document.addEventListener('visibilitychange', function(e) {
var isPageActive = document.visibilityState;
console.log(isPageActive);
if (isPageActive == "hidden") {
start_timer();
} else {
document.title = pageTitle;
clearInterval(blinkEvent);
}
})
function blink() {
document.title = appeal[appeal_index];
console.log(appeal[appeal_index]);
appeal_index++;
if (appeal_index >= appeal.length) { // wrap around to beginning
appeal_index = 0;
}
}
function start_timer() {
blink();
blinkEvent = setInterval(blink, 1900);
}
};

Conflit between setInterval and setTimeout

With an educational purpose I wrote the follow pice of code in JavaScript. The goal is to simulate a teletype machine and after the content is written the machine makes a pause before starts again.
var str = 'Some text';
strArray = str.split("");
window.onload = function teleType() {
var ctrl = 0;
var wrapId = document.getElementById("wrap");
var type = setInterval(function() {
wrapId.innerHTML += strArray[ctrl];
if (ctrl == strArray.length) {
wrapId.innerHTML = "";
ctrl = 0;
clearInterval(type);
}
ctrl++;
}, 2000);
setTimeout(teleType, 3000);
}
But with these intervals (mlliseconds) the machine begin to have an odd behavior. It jumps letters (index) or it starts from the begining without reach the end of the string (array). What is happening between the setInterval and the setTimeout ?
After setInterval is called you call setTimeout immediatelly.
As the result, you will trigger teleType before your interval completes.
You can move your setTimeout in the end of your interval:
var str = 'Some text';
strArray = str.split("");
window.onload = function teleType() {
var ctrl = 0;
var wrapId = document.getElementById("wrap");
var type = setInterval(function() {
wrapId.innerHTML += strArray[ctrl];
if (ctrl == strArray.length) {
wrapId.innerHTML = "";
ctrl = 0;
clearInterval(type);
setTimeout(teleType, 300);
}
ctrl++;
}, 200);
}
<div id="wrap"></div>
Now, teleType function runs interval, and when it finishes writing text it clears HTML content and tells browser to run teleType again in 2 seconds.
By the way, you don't need to set ctrl to 0, because it is local and will be reset anyway.
A sample function which outputs the text to console,
function showTeleText(text, repeat) {
var textByChar = text.split(''),
intermText = '',
textPos = 0;
var interval = setInterval(function () {
intermText += textByChar[textPos++]
console.log(intermText);
if (textPos >= textByChar.length) {
clearInterval(interval);
if (repeat) {
setTimeout(function () {
showTeleText(text, repeat);
}, 2000);
}
}
}, 500);
}
on window.load call showTeleText('Some text!', true/false) like,
window.load = function() {
showTeleText('Some text!', true);
}

Javascript Memory

I was wondering why my program crashes after its made its first match....any ideas would be greatly appreciated. Below is the code snippet. Thanks for the input!
var clicks = 0; //counts how may picks have been made in each turn
var firstchoice; //stores index of first card selected
var secondchoice; //stores index of second card selected
var match = 0; //counts matches made
var backcard = "deck.jpg"; //shows back of card when turned over
var faces = []; //array to store card images
faces[0] = 'pic1.jpg';
faces[1] = 'pic2.jpg';
faces[2] = 'pic3.jpg';
faces[3] = 'pic3.jpg';
faces[4] = 'pic2.jpg';
faces[5] = 'pic1.jpg';
function choose(card) {
if (clicks === 2) {
return;
}
if (clicks === 0) {
firstchoice = card;
document.images[card].src = faces[card];
clicks = 1;
} else {
clicks = 2;
secondchoice = card;
document.images[card].src = faces[card];
timer = setInterval("check()", 1000);
}
}
/* Check to see if a match is made */
function check() {
clearInterval(timer); //stop timer
if (faces[secondchoice] === faces[firstchoice]) {
match++;
document.getElementById("matches").innerHTML = match;
} else {
document.images[firstchoice].src = backcard;
document.images[secondchoice].src = backcard;
clicks = 0;
return;
}
}
The first parameter of setInterval needs to be a function not a string pretending to be a function. So you would want this:
timer = setInterval(function() { check(); }, 1000);
Of course, you can simplify:
timer = setInterval(check, 1000);
Not sure why you're using setInterval() here. You could more easily just do:
timer = setTimeout(check, 1000);
The advantage is there is no interval to clear in the check() function.
The other issue is that you are not resetting your 'clicks' counter to 0 when there is a match.
You want this:
function check() {
clearInterval(timer); //stop timer
if (faces[secondchoice] === faces[firstchoice]) {
match++;
document.getElementById("matches").innerHTML = match;
} else {
document.images[firstchoice].src = backcard;
document.images[secondchoice].src = backcard;
}
clicks = 0;
}
I think you have to declare you timer function globally. Its only defined in the scope of the first function, so in the second when you try to clear it nothing happens:
var timer = ''; //Declare timer up here first!
function choose(card) { ... }
function check() { ... }

how to use setTimeout or setInterval properly

I am using google maps and i am trying to put a pause in execution to prevent QUERY_LIMIT usage issue. My function that plots the addresses looks like this.
The code works, however i want to try setTimeout or setInterval to see if its going to look better on UI.
How do i call it, what should be the first argument?
Thanx alot.
vLocations = [];
for (var i = 0; i < vAddresses.length; i++) {
//pause to prevent OVER_QUERY_LIMIT issue
//geocode "free" usage limit is 5 requests per second
//setTimeout(PlotAddressesAsUnAssigned, 1000);
//sleep(500);
//this will resolve the address and store it in vLocations
AddWaypointAndUnassigned(vAddresses[i]);
var z = i % 4;
if (z==0 && i != 0) {
//sleep after every 5th geocode call
//alert('going to sleep...i: ' + i);
//sleep(3000);
}
}
Doing a pause (asynchronous execution) inside a loop (synchronous) will usually result in a lot of trouble.
You can use recursive calls that are done only when a timeout ends.
var vLocations = [];
// Manages the timeout and recursive calls
function AddWaypointAndUnassignedWithPause(index){
setTimeout(function(){
// When the timeout expires, we process the data, and start the next timeout
AddWaypointAndUnassigned(vAddresses[index]);
// Some other code you want to execute
var z = i % 4;
if (z==0 && i != 0) {
//sleep after every 5th geocode call
//alert('going to sleep...i: ' + i);
//sleep(3000);
}
if(index < vAddresses.length-1)
AddWaypointAndUnassignedWithPause(++index);
}, 1000);
}
// Start the loop
AddWaypointAndUnassignedWithPause(0);
JSFiddle example.
Try this, hope this will help
vLocations = [];
for (var i = 0; i < vAddresses.length; i++) {
//pause to prevent OVER_QUERY_LIMIT issue
setTimeout(function(){
//this will resolve the address and store it in vLocations
AddWaypointAndUnassigned(vAddresses[i]);
}, 500);
var z = i % 4;
if (z==0 && i != 0) {
//sleep after every 5th geocode call
//alert('going to sleep...i: ' + i);
//sleep(3000);
}
}
What about a waiting line, thats fired when an item is added and stopped when there are no items left.
With setTimeout:
var INTERVAL = 1000 / 5;
var to = null;
var vLocations = [];
function addAddress(vAddress) {
vLocations.push(vAddress);
startTimeout();
}
function startTimeout() {
if( to === null ) {
to = setTimout(processLocation, INTERVAL);
}
}
function processLocation() {
if( vLocations.length ) {
var vAddress = vLocations.shift();
AddWaypointAndUnassigned(vAddress);
to = setTimout(processLocation, INTERVAL);
} else {
to = null;
}
}
With setInterval:
var INTERVAL = 1000 / 5;
var to = null;
var vLocations = [];
function addAddress(vAddress) {
vLocations.push(vAddress);
startInterval();
}
function startInterval() {
if( to === null ) {
to = setInterval(processLocation, INTERVAL);
}
}
function processLocation(cb) {
if( vLocations.length ) {
var vAddress = vLocations.shift();
AddWaypointAndUnassigned(vAddress);
} else
clearInterval(to);
to = null;
}
}

JavaScript Sleep Function

I have a banner rotator that refreshes every 60 seconds however I would also like each banner to be displayed for 20 seconds as there are 3 of them. I know where to put the setInterval code as indicated by my comment but I can't seem to get it to work. Any help or suggestions are very much appreciated.
var banners1 = {
0:
{
'href': 'http://www.example.com/banner1.html',
'src': 'http://www.example.com/banner1.gif'
},
1:
{
'href': 'http://www.example.com/banner2.html',
'src': 'http://www.example.com/banner2.gif'
},
2:
{
'href': 'http://www.example.com/banner3.html',
'src': 'http://www.example.com/banner3.gif'
}
}
window.addEvent('domready', function() {
function banner1()
{
var banner = $('banner1');
var banner1Link = $('banner1').getElement('a');
var banner1Image = $('banner1').getElement('img');
for (var keys in banners1) {
var object = banners1[keys];
for (var property in object) {
if (property == 'href') {
var href = object[property];
}
if (property == 'src') {
var src = object[property];
}
}
banner1Link.setProperty('href', href);
banner1Image.setProperty('src', src);
console.log(href);
console.log(src);
/** wait 20 seconds **/
}
}
var periodical = banner1.periodical(60000);
});
Try this instead:
function banner1()
{
var banner = $('banner1');
var banner1Link = $('banner1').getElement('a');
var banner1Image = $('banner1').getElement('img');
var delay = 0;
for (var keys in banners1) {
var func = (function(key) { return function() {
var object = banners1[key];
for (var property in object) {
if (property == 'href') {
var href = object[property];
}
if (property == 'src') {
var src = object[property];
}
}
banner1Link.setProperty('href', href);
banner1Image.setProperty('src', src);
console.log(href);
console.log(src);
}; })(keys);
setTimeout(func, delay);
delay += 20000;
}
}
JavaScript does not have a sleep-style function, because the document will not respond while JavaScript is running. This means the user would not be able to interact with the page while the script is sleeping.
This approach schedules all three updates in one shot. They will execute at 0 seconds (immediately), 20 seconds, and 40 seconds from the time the script runs.
you could use the javascript timeout
setTimeout('', 20000);
This would be added right after the 20 sec comment. The first variable is any code/function you want called. and the second is the amount of time required before it is called in milliseconds (20 secs).
EDITED ANSWER
<script type="text/javascript">
var imgs1 = new Array("http://www.omniadiamond.com/images/jwplayer/enel_culture.png","http://www.omniadiamond.com/images/jwplayer/evas_srm.png","http://www.omniadiamond.com/images/jwplayer/jackolantern.png");
var lnks1 = new Array("http://test.com","http://test.com","http://test.com");
var alt1 = new Array("test","test","test");
var currentAd1 = 0;
var imgCt1 = 3;
function cycle1() {
if (currentAd1 == imgCt1) {
currentAd1 = 0;
}
var banner1 = document.getElementById('adBanner1');
var link1 = document.getElementById('adLink1');
banner1.src=imgs1[currentAd1]
banner1.alt=alt1[currentAd1]
document.getElementById('adLink1').href=lnks1[currentAd1]
currentAd1++;
}
window.setInterval("cycle1()",20000);
</script>
<a href="http://test.com" id="adLink1" target="_top">
<img src="http://www.omniadiamond.com/images/jwplayer/enel_culture.png" id="adBanner1" border="0"></a>
This does cycle through all three in 60 secs at a 20 sec interval. and can be viewed at http://jsfiddle.net/jawilliams346614/wAKGp/ (it is set to a 1 sec interval)

Categories