JavaScript Sleep Function - javascript

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)

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);
}
};

Javascript two interval image change

I have an image that I want to stay on screen for 5 seconds and then change to another image for .5 of a second and then change back to the original.
I've set the interval to change every 5 seconds but I can't seem to work out how to make it change for the according times.
Any help or direction would be greatly appeciated!
window.setInterval(function() {
var img = document.getElementById("glitch");
img.src = "2-01.svg";
}, 5000);
Try this:
const images = ["1.svg", "2.svg"]
var element = document.getElementById("glitch");
function showFirst() {
setTimeout(() => {
element.src = images[0];
showSecond()
}, 5000)
}
function showSecond() {
setTimeout(() => {
element.src = images[1];
showFirst()
}, 500)
}
showFirst()
You are always changing the image src to same "2-01.svg" every time. Please use some flag/condition to alternate the image src.
Here is what you can try ::
window.setInterval(function() {
var img = document.getElementById("glitch");
if(img.src == "2-01.svg") {
img.src = "2-00.svg"
}
else {
img.src = "2-01.svg";
}
}, 5000);
I was doing some test watching the thread.
If that can help you (this is not a clean code) :
img_to_change = document.querySelector("#glitch");
imgs = {"a":10, "b":2, "c":3}
keys = Object.keys(imgs)
run = function(i){
img_src = keys[i];
img_next_time = imgs[keys[i]];
img_to_change.src = img_src;
i = (i+1) == keys.length ? -1 : i;
setTimeout(() => {
img_to_change.src = img_src;
run(i+1);
}, img_next_time*1000)
}
run(0);
http://jsfiddle.net/pn3dyb5m/32/

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

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...

Javascript - countdown timer is incrementing not persecond

Can anyone tell me what am i doing wrong? i have the timer which is displaying with 2 or 3 or 4 seconds at once increment instead of per second.
var call_s = 0;
var call_m = 0;
var call_h = 0;
var call_connected = null;
var display = null ;
function connected_timer_start(tototo) {
call_connected = setTimeout(function() {
call_s++;
if (call_s>59) {
call_s = 0;
call_m++;
}
if (call_m>59){
call_m = 0;
call_h++;
}
display = (call_h < 10 ? '0' : '') + call_h + ':' +
(call_m < 10 ? '0' : '') + call_m + ':' +
(call_s < 10 ? '0' : '') + call_s;
console.log(display);
connected_timer_start();
}, 1000);
}
function connected_timer_stop() {
call_s = 0;
call_m = 0;
call_h = 0;
clearTimeout(call_connected);
call_connected = null;
document.getElementById('display').style.display = 'none';
}
As jfriend00 said, you shouldn't use setTimeout() to figure out the time values, because it's not reliable. A version of code that uses Date() is actually shorter and simpler:
var begining_timestamp = null;
var call_connected = null;
var call_ms = null;
var display = null ;
function connected_timer_start() {
if (call_connected==null) {
begining_timestamp = (new Date()).getTime();
count();
} else {
console.log('One timer is already started!');
}
}
function count() {
call_connected = setTimeout(function() {
getCallLength();
count();
}, 1000);
}
function getCallLength() {
call_ms = (new Date()).getTime() - begining_timestamp;
var tmp_date = new Date(null);
tmp_date.setSeconds(call_ms/1000);
display = tmp_date.toISOString().substr(11, 8);
console.log(display);
}
function connected_timer_stop() {
clearTimeout(call_connected);
getCallLength();
call_connected = null;
document.getElementById('display').style.display = 'none';
}
I see several advantages to this approach:
times are accurate even if setTimeout triggers every 2 seconds or at random times, your call duration will be accurate
the call duration gets updated when the call ends, to make sure it's completely accurate
you have the call time down to milliseconds, if you ever need that
the call_ms variable does not get cleared when a call ends, but when a call starts; that means between two calls, you can always have the last call length expressed in milliseconds
as AlexAtNet suggested, you may start the timer more than once, by mistake; so connected_timer_start now checks if the timer is not already started

Run URL one by one in For loop

I have several URLs in my array and I want to run it one by one,
but when I run it in a loop, it executes all at the same time and does not wait.
Here is what I tried:
<html>
<head>
<script>
function work(){
var otherStoryLinksArray = [];
otherStoryLinksArray[0] = 'http://google.com';
otherStoryLinksArray[1] = 'http://www.yahoo.com';
otherStoryLinksArray[2] = 'http://gmail.com';
for(var i=0;i<3;i++){
var openWindow = window.open(otherStoryLinksArray[i]);
setTimeout(function(){openWindow.close();},3000);
}
}
</script>
</head>
<body onload=work();>
</body>
</html>
I want it to open one URL, wait for 30 secs, close the popup, and then start another URL.
Waiting for your reply guys. Any help would be appreciated thanks...
Code: http://jsfiddle.net/WgR4y/1/
Demo: http://jsfiddle.net/WgR4y/1/show/ (make sure you disable popup blocker)
Works for unlimited number of URLs in array.
var otherStoryLinksArray = [
'http://google.com',
'http://www.yahoo.com',
'http://gmail.com'
],
timeToCloseWindow = 3000;
function work() {
if(otherStoryLinksArray.length==0) return;
var url = otherStoryLinksArray.shift();
var openWindow = window.open(url);
setTimeout(function () {
openWindow.close();
work();
}, timeToCloseWindow);
}
work();
You need to stagger your setTimeout calls and since setTimeout uses ms, 30 s = 30000 ms:
function work () {
var otherStoryLinksArray = [];
otherStoryLinksArray[0] = 'http://google.com';
otherStoryLinksArray[1] = 'http://www.yahoo.com';
otherStoryLinksArray[2] = 'http://gmail.com';
for(var i=0; i<3; i++) {
var openWindow;
setTimeout(function () {
openWindow = window.open(otherStoryLinksArray[i]);
}, 30000 * i); //Open this window
setTimeout(function () {
openWindow.close();
}, 30000 * i + 30000); //Close it 30 seconds from "now"
}
}
Use set interval instead of for-loop
function work(){
var otherStoryLinksArray = [];
otherStoryLinksArray[0] = 'http://google.com';
otherStoryLinksArray[1] = 'http://www.yahoo.com';
otherStoryLinksArray[2] = 'http://gmail.com';
var myVar=setInterval(function(){myTimer()},3000);
var i=0;
var openWindow;
function myTimer()
{
if(openWindow != null)
openWindow.close();
if(i < 3)
{
openWindow = window.open(otherStoryLinksArray[i]);
i++;
}
else
clearInterval(myVar);
}
}
var otherStoryLinksArray = [
'http://google.com',
'http://www.yahoo.com',
'http://gmail.com'];
var i = 0;
var openedWindow = null;
function loop(){
openedWindow && openedWindow.close();
if(otherStoryLinksArray[i]){
var openedWindow = window.open(otherStoryLinksArray[i]);
i++;
setTimeout(loop,30000);
}
}

Categories