Conflit between setInterval and setTimeout - javascript

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

Related

Stop the running script

I run a script in the browser that scrolls the page down. I run it from the browser console (ctrl + shift + j).
var popWys = 0;
var terazWys = 0;
var proba = 0;
function scrollowanie() {
if(popWys == document.body.scrollHeight)
{
proba++;
if(proba > 10)
{
window.alert("To juz chyba wszystko, w razie czego odpal ponownie.");
return;
}
}
else
{
proba = 0;
}
popWys = document.body.scrollTop;
terazWys += 1000;
window.scrollTo(0,terazWys);
setTimeout(scrollowanie, 100);
}
setTimeout(scrollowanie, 100);
Question. How to stop it at any time from the command line? Can I write something, press to stop? Sam will never stop and blocks the browser. I tried with different: return; break; Stop. anything and nothing works.
Can it be done at all?
You can use clearTimeout([variable name]) to stop the setTimeout(scrollowanie, 100);
Just assign setTimeout(scrollowanie, 100); to global variable like following:
globalVar = setTimeout(scrollowanie, 100);
And in the console type clearTimeout(globalVar) and the execution will finish
You could wrap desired behaviour in an object that handles the process.
e.g.:
var script = (function () {
var timeout;
var DESIRED_TIME = 100;
function scrollowanie() {
console.log('::Testing');
// Desired behaviour here
clearTimeout(timeout);
timeout = setTimeout(scrollowanie, DESIRED_TIME)
}
return {
start: function() {
timeout = setTimeout(scrollowanie, DESIRED_TIME);
},
stop: function () {
clearTimeout(timeout);
}
}
})();
Then in the command line you will just need to start the process
script.start();
and to end it
script.stop();

update a delayed function in javascript

I have a simple javascript function that loads on document ready:
var start = 1;
var speed = 1000;
$(document).ready(function () {
go();
setInterval(function () {
go();
}, speed);
This is the function in details:
function go() {
$("#score").html(start.toLocaleString());
start += 1;
}
This is basically a counter which starts from number 1 to infinite, at 1000 milliseconds speed. Here is the thing , now: I have another function:
function modify() {
speed = 500;
}
which regulates the setIntval speed on the main function. The problem is it applies on page refresh only. How do I update it in real time without refreshing page?
You can't update the current one, you have to stop it and set a new timer, which does the same but with a different delay.
var speed = 1000;
var start = 1;
function go() {
$("#score").html(start.toLocaleString());
start += 1;
}
function startGoTimer(){
return = setInterval(function () {
go();
}, speed);
}
function modifyTimer( previousTimer, newDelay=500) {
clearInterval(previousTimer);
speed = newDelay;
startGoTimer();
}
var timer = startGoTimer();
// Some code
modifyTimer(timer, 500);
For fun I just tested what would hapopen if you just change the time:
var timing = 1000;
var interval = setInterval(function(){console.log("test")}, timing);
// Now we get a log every 1000ms, change the var after some time (via console):
timing = 10;
// still an interval of 1000ms.
A really simple solution is to make use of the setInterval's parameters,
var intervalID = scope.setInterval(func, delay[, param1, param2, ...]);
and also pass the speed as param1.
Then, at each interval, check if it changed, and if, clear the existing timer and fire up a new.
Stack snippet
var start = 1;
var speed = 1000;
var timer;
$(document).ready(function() {
go();
timer = setInterval(function(p) {
go(p);
}, speed, speed);
// for this demo
$("button").click(function(){ speed = speed/2});
})
function go(p) {
if(p && p != speed) {
clearInterval(timer);
timer = setInterval(function(p) {
go(p);
}, speed, speed);
}
$("#score").html(start.toLocaleString());
start += 1;
}
div {
display: inline-block;
width: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="score">0</div>
<button>Modify</button>

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

SetInterval doesn't same when called again?

I'm making a simple program which increases a number incrementally for every 0.5 second. When I click start it works perfectly. But when I click restart, the increments go fine, but they don't increment every 0.5 sec and go pretty fast, and this happens when I am calling the same function? JS fiddle link below.
function runFunc(){
declare a variable interval outside function
var myInterval = null;
check if an interval is already running if yes clear it in order to avoid multiple interval running the same function which makes the interval became looks faster than the first time it's called
if (myInterval != null) {
clearInterval(myInterval);
}
also this is not correct
clearInterval(varName);
the parameter should be an interval which is like this
clearInterval(myInterval);
so your javascript code would be like this
var myInterval = null;
function runFunc(){
$('#counter').val(zero);
var varName = function(){
var number = Number($('#number').val());
var counter = Number($('#counter').val());
if(counter < number) {
counter++;
console.log(counter);
$('#counter').val(counter);
} else {
clearInterval(myInterval);
}
};
//check if an interval is already running if yes clear it
if (myInterval != null) {
clearInterval(myInterval);
}
myInterval = setInterval(varName, 500);
};
show.click(runFunc);
reset.click(function(){
$('#number').val(zero);
$('#counter').val(zero);
});
restart.click(runFunc);
u have to Declare a Variable for setInterval like "setIntervalID"
so stop it clearInterval("setIntervalID");
JSFIDDLE
var initialNumber = 10;
var zero = 0;
$('#number').val(initialNumber);
$('#counter').val(zero);
var show = $('#show');
var reset = $('#reset');
var restart = $('#restart');
var setIntervalID;
// console.log('initial value of number is ' + number);
// console.log(typeof number);
// console.log('initial value of counter is ' + counter);
var varName = function(){
var number = Number($('#number').val());
var counter = Number($('#counter').val());
if(counter < number) {
counter++;
console.log(counter);
$('#counter').val(counter);
}
}
function runFunc(){
$('#counter').val(zero);
setIntervalID = setInterval(varName, 500);
};
function stopFunc(){
clearInterval(setIntervalID);
};
function restartGO(){
stopFunc();
runFunc();
}
show.click(runFunc);
restart.click(restartGO);
reset.click(function(){
$('#number').val(zero);
$('#counter').val(zero);
});

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