The console is showing errors on lines 5 and 8. The error is "Uncaught insert function argument is not a string." Any help would be greatly appreciated. Thanks!
$(function() {
var animation = false;
function typed(term, message, delay, finish) {
animation = true;
var da = 0;
term.set_prompt('');
var interval = setInterval(function() {
term.insert(message[da++]);
if(da > message.length) {
clearInterval(interval);
setTimeout(function() {
term.set_command('')
term.set_prompt(message + ' ');
animation = false;
finish && finish();
}, delay);
}
}, delay);
}
$('#fyeah').terminal(function(cmd, term) {
var finish = false;
}, {
name: 'test',
greetings: null,
onInit: function(term) {
var msg = "testing";
typed(term, msg, 150, function() {
finish = true;
});
},
keydown: function(e) {
if (animation) {
return false;
}
}
});
});
There are three cases when message[da++] "is not a string":
message is the empty string
(old) IE do not support bracket notation for getting single characters of strings, better use the .charAt() method
in the last iteration of your loop, da == message.length - it ends only when da is already greater than the length. Yet, the indices are zero-based and run from 0 to length-1.
To fix it, use
// init
var da = 0;
var interval = setInterval(function() {
if (da < message.length) {
term.insert(message.charAt(da++)); // maybe better move the incrementing
// out, to the end of the loop
} else {
clearInterval(interval);
// teardown / callback
}
}, delay);
Related
I've built a series of timers that are designed to be started, paused and resumed on cue. Numbers update dynamically on my page when the timer ticks up. The issue I'm having is figuring out how to get the timer to start from where it left off before I paused it. I can get it to restart from scratch, but I unsure how to take the paused Date.now() value, and work it into the formula to display the correct value. It will be something stupid that I just cant figure out.
function ticking2(num) {
//IF TIMER IS PAUSED CANCEL THE ANIMATION FRAME
if (timerObjArray[num].paused == true) {
timerObjArray[num].restartTime = Date.now();
cancelAnimationFrame(id);
} else if (timerObjArray[num].paused == false) {
timerObjArray[num].initialTime = Date.now()
if (timerObjArray[num].restartTime != 0) {
//THIS IS THE LINE WHERE I AM HAVING TROUBLE
timerObjArray[num].milli = ((timerObjArray[num].initialTime - timerObjArray[num].initialDate) - (timerObjArray[num].initialTime - timerObjArray[num].restartTime)) / 1000;
} else {
timerObjArray[num].milli = ((timerObjArray[num].initialTime - timerObjArray[num].initialDate ) / 1000);
}
//THIS FUNCTION TAKES THE MS VALUE AND CONVERTS IT TO HH:MM:SS
convert(num, timerObjArray[num].milli * 1000);
id = requestAnimationFrame(function() {
ticking2(num);
});
}
}
Thanks for the help.
I don't have enough information so, I made a simple implementation. You can look at this to help determine what you're missing. You're welcome to use it.
Timer fiddle
Utility:
var timer = (function() {
let _timers = {};
let pub = {
start : function(id) {
if(!_timers[id]) _timers[id] = {on:true, intervals:[{start:new Date()}] };
else if(_timers[id].on) throw 'timer is already started: ' + id;
else {
_timers[id].on = true;
_timers[id].intervals.push({start:new Date()});
}
},
stop : function(id) {
if(!_timers[id]) throw 'timer does not exist, cannot be stopped: ' + id;
else if(!_timers[id].on) throw 'timer is already stopped: ' + id;
else {
_timers[id].on = false;
let interval = _timers[id].intervals[_timers[id].intervals.length -1];
interval.stop = new Date();
interval.total = interval.stop - interval.start;
}
},
read : function(id) {
if(!_timers[id]) throw 'timer does not exist, cannot be read: ' + id;
let total = 0;
for(let i=0; i<_timers[id].intervals.length; i++) {
if(_timers[id].intervals[i].total) total += _timers[id].intervals[i].total;
else total += (new Date()) - _timers[id].intervals[i].start;
}
return { intervals:_timers[id].intervals, total: total };
},
delete: function(id) {
if(!_timers[id]) throw 'timer does not exist, cannot be deleted: ' + id;
delete _timers[id];
}
};
return pub;
})();
Example usage:
$('.start').on('click', function(){
timer.start(123);
});
$('.stop').on('click', function(){
timer.stop(123);
});
$('.clear').on('click', function(){
timer.delete(123);
$('input').val('');
});
setInterval(function(){
let result = null;
try//obviously not a great pattern
{
result = timer.read(123);
} catch(ex){}
if(result) {
$('input').val(result.total);
}
}, 35);
I have small function that adds class to elements in array every 100ms
var index = 0;
var $pcs = $('.participant');
var setWinCls = {
start: function(i){
if(i>0){
$pcs.eq(i-1).removeClass('winner');
}
if(i == $pcs.length){
i=0;
}
$pcs.eq(i).addClass('winner');
setTimeout(function() { setWinCls.start(i+1) },100);
},
stop: function () {
...
}
};
I'm trying to define stop method with will stop adding class on elements and stops on last added element or element I will point. Any suggestions?
I tried use return false but it didn't helped.
Add a flag (stopped) to setWinCls, and use the stop method to change it to true. As long as stopped is false, the setTimeout will be called:
var $pcs = $('.participant');
var setWinCls = {
stopped: false, // the flag
start: function(i) {
if (i > 0) {
$pcs.eq(i - 1).removeClass('winner');
}
if (i == $pcs.length) {
i = 0;
}
$pcs.eq(i).addClass('winner');
// if stopped is false, setTimeout will be called
this.stopped || setTimeout(function() {
setWinCls.start(i + 1)
}, 100);
},
stop: function() {
this.stopped = true; // changing stopped to true
}
};
I am trying to use typed.js to give example cities in this text input box. My goal is to have it completely stop the animation when it is clicked on. How would I go about this?
This is my attempt at it.
JS:
$(document).ready(function(){
$(function()
{
$("#input_text").typed(
{
strings: ["^2000", "New York City^2000", "Berlin^2000", "London^2000", "Hong Kong^2000", "Chicago^2000", ""],
typeSpeed: 50
});
});
$( "#input_text" ).click(function()
{
$( "#input_text" ).stop();
});
});
I'm pretty new to javascript so could you please tell me how to accomplish my goal?
From the source code:
Start & Stop currently not working
So If you need to stop by hand a trick that I do not suggest you is to remap external the timeout function this plugin use or fork the plugin itself (this is my suggestion).
For manipulating the timeout externally you can do something like:
var _setTimeout;
var _clearTimeout;
var _pauseOn;
_setTimeout = window.setTimeout;
_clearTimeout = window.clearTimeout;
window.setTimeout = function(code, delay) {
return _setTimeout(function () {
if (_pauseOn == true) {
return;
}
code();
}, delay);
};
window.clearTimeout = function(intervalId) {
if (_pauseOn == true) {
return;
}
_clearTimeout(intervalId);
};
function pauseTimer() {
_pauseOn = true;
}
........
$( "#input_text" ).click(function() {
pauseTimer();
});
In the following the snippet.
//-----------------------
// avoid or fork
//
var _setTimeout;
var _clearTimeout;
var _pauseOn;
_setTimeout = window.setTimeout;
_clearTimeout = window.clearTimeout;
window.setTimeout = function(code, delay) {
return _setTimeout(function () {
if (_pauseOn == true) {
return;
}
code();
}, delay);
};
window.clearTimeout = function(intervalId) {
if (_pauseOn == true) {
return;
}
_clearTimeout(intervalId);
};
function pauseTimer() {
_pauseOn = true;
}
//-----------------------
// avoid or fork
//
$(function () {
$("#input_text").typed({
strings: ["^2000", "New York City^2000", "Berlin^2000", "London^2000", "Hong Kong^2000", "Chicago^^2000", ""],
typeSpeed: 50
});
$( "#input_text" ).click(function() {
pauseTimer();
$( "#input_text").val('');
});
});
input{
font-size:3em;
}
.typed-cursor{
opacity: 1;
-webkit-animation: blink 0.7s infinite;
-moz-animation: blink 0.7s infinite;
animation: blink 0.7s infinite;
}
#keyframes blink{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
#-webkit-keyframes blink{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
#-moz-keyframes blink{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
<script src="//code.jquery.com/jquery-1.11.3.js"></script>
<script>
// The MIT License (MIT)
// Typed.js | Copyright (c) 2014 Matt Boldt | www.mattboldt.com
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
! function($) {
"use strict";
var Typed = function(el, options) {
// chosen element to manipulate text
this.el = $(el);
// options
this.options = $.extend({}, $.fn.typed.defaults, options);
// attribute to type into
this.isInput = this.el.is('input');
this.attr = this.options.attr;
// show cursor
this.showCursor = this.isInput ? false : this.options.showCursor;
// text content of element
this.elContent = this.attr ? this.el.attr(this.attr) : this.el.text()
// html or plain text
this.contentType = this.options.contentType;
// typing speed
this.typeSpeed = this.options.typeSpeed;
// add a delay before typing starts
this.startDelay = this.options.startDelay;
// backspacing speed
this.backSpeed = this.options.backSpeed;
// amount of time to wait before backspacing
this.backDelay = this.options.backDelay;
// div containing strings
this.stringsElement = this.options.stringsElement;
// input strings of text
this.strings = this.options.strings;
// character number position of current string
this.strPos = 0;
// current array position
this.arrayPos = 0;
// number to stop backspacing on.
// default 0, can change depending on how many chars
// you want to remove at the time
this.stopNum = 0;
// Looping logic
this.loop = this.options.loop;
this.loopCount = this.options.loopCount;
this.curLoop = 0;
// for stopping
this.stop = false;
// custom cursor
this.cursorChar = this.options.cursorChar;
// shuffle the strings
this.shuffle = this.options.shuffle;
// the order of strings
this.sequence = [];
// All systems go!
this.build();
};
Typed.prototype = {
constructor: Typed
,
init: function() {
// begin the loop w/ first current string (global self.strings)
// current string will be passed as an argument each time after this
var self = this;
self.timeout = setTimeout(function() {
for (var i=0;i<self.strings.length;++i) self.sequence[i]=i;
// shuffle the array if true
if(self.shuffle) self.sequence = self.shuffleArray(self.sequence);
// Start typing
self.typewrite(self.strings[self.sequence[self.arrayPos]], self.strPos);
}, self.startDelay);
}
,
build: function() {
var self = this;
// Insert cursor
if (this.showCursor === true) {
this.cursor = $("<span class=\"typed-cursor\">" + this.cursorChar + "</span>");
this.el.after(this.cursor);
}
if (this.stringsElement) {
self.strings = [];
this.stringsElement.hide();
var strings = this.stringsElement.find('p');
$.each(strings, function(key, value){
self.strings.push($(value).html());
});
}
this.init();
}
// pass current string state to each function, types 1 char per call
,
typewrite: function(curString, curStrPos) {
// exit when stopped
if (this.stop === true) {
return;
}
// varying values for setTimeout during typing
// can't be global since number changes each time loop is executed
var humanize = Math.round(Math.random() * (100 - 30)) + this.typeSpeed;
var self = this;
// ------------- optional ------------- //
// backpaces a certain string faster
// ------------------------------------ //
// if (self.arrayPos == 1){
// self.backDelay = 50;
// }
// else{ self.backDelay = 500; }
// contain typing function in a timeout humanize'd delay
self.timeout = setTimeout(function() {
// check for an escape character before a pause value
// format: \^\d+ .. eg: ^1000 .. should be able to print the ^ too using ^^
// single ^ are removed from string
var charPause = 0;
var substr = curString.substr(curStrPos);
if (substr.charAt(0) === '^') {
var skip = 1; // skip atleast 1
if (/^\^\d+/.test(substr)) {
substr = /\d+/.exec(substr)[0];
skip += substr.length;
charPause = parseInt(substr);
}
// strip out the escape character and pause value so they're not printed
curString = curString.substring(0, curStrPos) + curString.substring(curStrPos + skip);
}
if (self.contentType === 'html') {
// skip over html tags while typing
var curChar = curString.substr(curStrPos).charAt(0)
if (curChar === '<' || curChar === '&') {
var tag = '';
var endTag = '';
if (curChar === '<') {
endTag = '>'
} else {
endTag = ';'
}
while (curString.substr(curStrPos).charAt(0) !== endTag) {
tag += curString.substr(curStrPos).charAt(0);
curStrPos++;
}
curStrPos++;
tag += endTag;
}
}
// timeout for any pause after a character
self.timeout = setTimeout(function() {
if (curStrPos === curString.length) {
// fires callback function
self.options.onStringTyped(self.arrayPos);
// is this the final string
if (self.arrayPos === self.strings.length - 1) {
// animation that occurs on the last typed string
self.options.callback();
self.curLoop++;
// quit if we wont loop back
if (self.loop === false || self.curLoop === self.loopCount)
return;
}
self.timeout = setTimeout(function() {
self.backspace(curString, curStrPos);
}, self.backDelay);
} else {
/* call before functions if applicable */
if (curStrPos === 0)
self.options.preStringTyped(self.arrayPos);
// start typing each new char into existing string
// curString: arg, self.el.html: original text inside element
var nextString = curString.substr(0, curStrPos + 1);
if (self.attr) {
self.el.attr(self.attr, nextString);
} else {
if (self.isInput) {
self.el.val(nextString);
} else if (self.contentType === 'html') {
self.el.html(nextString);
} else {
self.el.text(nextString);
}
}
// add characters one by one
curStrPos++;
// loop the function
self.typewrite(curString, curStrPos);
}
// end of character pause
}, charPause);
// humanized value for typing
}, humanize);
}
,
backspace: function(curString, curStrPos) {
// exit when stopped
if (this.stop === true) {
return;
}
// varying values for setTimeout during typing
// can't be global since number changes each time loop is executed
var humanize = Math.round(Math.random() * (100 - 30)) + this.backSpeed;
var self = this;
self.timeout = setTimeout(function() {
// ----- this part is optional ----- //
// check string array position
// on the first string, only delete one word
// the stopNum actually represents the amount of chars to
// keep in the current string. In my case it's 14.
// if (self.arrayPos == 1){
// self.stopNum = 14;
// }
//every other time, delete the whole typed string
// else{
// self.stopNum = 0;
// }
if (self.contentType === 'html') {
// skip over html tags while backspacing
if (curString.substr(curStrPos).charAt(0) === '>') {
var tag = '';
while (curString.substr(curStrPos).charAt(0) !== '<') {
tag -= curString.substr(curStrPos).charAt(0);
curStrPos--;
}
curStrPos--;
tag += '<';
}
}
// ----- continue important stuff ----- //
// replace text with base text + typed characters
var nextString = curString.substr(0, curStrPos);
if (self.attr) {
self.el.attr(self.attr, nextString);
} else {
if (self.isInput) {
self.el.val(nextString);
} else if (self.contentType === 'html') {
self.el.html(nextString);
} else {
self.el.text(nextString);
}
}
// if the number (id of character in current string) is
// less than the stop number, keep going
if (curStrPos > self.stopNum) {
// subtract characters one by one
curStrPos--;
// loop the function
self.backspace(curString, curStrPos);
}
// if the stop number has been reached, increase
// array position to next string
else if (curStrPos <= self.stopNum) {
self.arrayPos++;
if (self.arrayPos === self.strings.length) {
self.arrayPos = 0;
// Shuffle sequence again
if(self.shuffle) self.sequence = self.shuffleArray(self.sequence);
self.init();
} else
self.typewrite(self.strings[self.sequence[self.arrayPos]], curStrPos);
}
// humanized value for typing
}, humanize);
}
/**
* Shuffles the numbers in the given array.
* #param {Array} array
* #returns {Array}
*/
,shuffleArray: function(array) {
var tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
// Start & Stop currently not working
// , stop: function() {
// var self = this;
// self.stop = true;
// clearInterval(self.timeout);
// }
// , start: function() {
// var self = this;
// if(self.stop === false)
// return;
// this.stop = false;
// this.init();
// }
// Reset and rebuild the element
,
reset: function() {
var self = this;
clearInterval(self.timeout);
var id = this.el.attr('id');
this.el.after('<span id="' + id + '"/>')
this.el.remove();
if (typeof this.cursor !== 'undefined') {
this.cursor.remove();
}
// Send the callback
self.options.resetCallback();
}
};
$.fn.typed = function(option) {
return this.each(function() {
var $this = $(this),
data = $this.data('typed'),
options = typeof option == 'object' && option;
if (!data) $this.data('typed', (data = new Typed(this, options)));
if (typeof option == 'string') data[option]();
});
};
$.fn.typed.defaults = {
strings: ["These are the default values...", "You know what you should do?", "Use your own!", "Have a great day!"],
stringsElement: null,
// typing speed
typeSpeed: 0,
// time before typing starts
startDelay: 0,
// backspacing speed
backSpeed: 0,
// shuffle the strings
shuffle: false,
// time before backspacing
backDelay: 500,
// loop
loop: false,
// false = infinite
loopCount: false,
// show cursor
showCursor: true,
// character for cursor
cursorChar: "|",
// attribute to type (null == text)
attr: null,
// either html or text
contentType: 'html',
// call when done callback function
callback: function() {},
// starting callback function before each string
preStringTyped: function() {},
//callback for every typed string
onStringTyped: function() {},
// callback for reset
resetCallback: function() {}
};
}(window.jQuery);
</script>
<input id="input_text" type="text" placeholder="" />
you can replace it like
$('#input_text').on('click', function(e){
$(this).data('typed').reset();
$('#input_text').replaceWith('<input type="text" name="q" size="25" id="input_text" value=""/>');
$("#input_text").focus();
});
I am trying to figure out a way to make my countdown timer restart at 25 all over again when it reaches 0. I dont know what I am getting wrong but it wont work.
Javascript
window.onload = function() {
startCountDown(25, 1000, myFunction);
}
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
//write out count
countDownObj.innerHTML = i;
if (i == 0) {
//execute function
fn();
//stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
},
pause
);
}
//set it going
countDownObj.count(i);
}
function myFunction(){};
</script>
HTML
<div id="countDown"></div>
try this, timer restarts after 0
http://jsfiddle.net/GdkAH/1/
Full code:
window.onload = function() {
startCountDown(25, 1000, myFunction);
}
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
startCountDown(25, 1000, myFunction);
// stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
}, pause);
}
// set it going
countDownObj.count(i);
}
function myFunction(){};
I don't see you resetting the counter. When your counter goes down to 0, it executes the function and return. Instead, you want to execute the function -> reset the counter -> return
You can do this by simply adding i = 25 under fn() :
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
i = 25;
// stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
},
pause
);
}
// set it going
in #Muthu Kumaran code is not showing zero after countdown 1 . you can update to this:
if (i < 0) {
// execute function
fn();
startCountDown(10, 1000, myFunction);
// stop
return;
}
The main reason for using setInterval for a timer that runs continuously is to adjust the interval so that it updates as closely as possible to increments of the system clock, usually 1 second but maybe longer. In this case, that doesn't seem to be necessary, so just use setInterval.
Below is a function that doesn't add non–standard properties to the element, it could be called using a function expression from window.onload, so avoid global variables altogether (not that there is much point in that, but some like to minimise them).
var runTimer = (function() {
var element, count = 0;
return function(i, p, f) {
element = document.getElementById('countDown');
setInterval(function() {
element.innerHTML = i - (count % i);
if (count && !(count % i)) {
f();
}
count++;
}, p);
}
}());
function foo() {
console.log('foo');
}
window.onload = function() {
runTimer(25, 1000, foo);
}
I want to have two functions (an animation downwards and animation upwards) executing one after the other in a loop having a timeout of a few seconds between both animations. But I don't know how to say it in JS …
Here what I have so far:
Function 1
// Play the Peek animation - downwards
function peekTile() {
var peekAnimation = WinJS.UI.Animation.createPeekAnimation([tile1, tile2]);
// Reposition tiles to their desired post-animation position
tile1.style.top = "-150px";
tile2.style.top = "-150px";
peekAnimation.execute();
}
Function 2
// Play the Peek animation - upwards
function unpeekTile() {
var peekAnimation = WinJS.UI.Animation.createPeekAnimation([tile1, tile2]);
// Reposition tiles to their desired post-animation position
tile1.style.top = "0px";
tile2.style.top = "0px";
peekAnimation.execute();
}
And here's a sketch how both functions should be executed:
var page = WinJS.UI.Pages.define("/html/updateTile.html", {
ready: function (element, options) {
peekTile();
[timeOut]
unpeekTile();
[timeOut]
peekTile();
[timeOut]
unpeekTile();
[timeOut]
and so on …
}
});
You can do this using setTimeout or setInterval, so a simple function to do what you want is:
function cycleWithDelay() {
var delay = arguments[arguments.length - 1],
functions = Array.prototype.slice.call(arguments, 0, arguments.length - 1),
pos = 0;
return setInterval(function () {
functions[pos++]();
pos = pos % functions.length;
}, delay);
}
Usage would be like this for you:
var si = cycleWithDelay(peekTile, unpeekTile, 300);
and to stop it:
clearInterval(si);
This will just cycle through the functions calling the next one in the list every delay msec, repeating back at the beginning when the last one is called. This will result in your peekTile, wait, unpeekTile, wait, peekTile, etc.
If you prefer to start/stop at will, perhaps a more generic solution would suit you:
function Cycler(f) {
if (!(this instanceof Cycler)) {
// Force new
return new Cycler(arguments);
}
// Unbox args
if (f instanceof Function) {
this.fns = Array.prototype.slice.call(arguments);
} else if (f && f.length) {
this.fns = Array.prototype.slice.call(f);
} else {
throw new Error('Invalid arguments supplied to Cycler constructor.');
}
this.pos = 0;
}
Cycler.prototype.start = function (interval) {
var that = this;
interval = interval || 1000;
this.intervalId = setInterval(function () {
that.fns[that.pos++]();
that.pos %= that.fns.length;
}, interval);
}
Cycler.prototype.stop = function () {
if (null !== this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
Example usage:
var c = Cycler(peekTile, unpeekTile);
c.start();
// Future
c.stop();
You use setInterval() to call unpeekTile() every 1000 milliseconds and then you call setTimeOut() to run peekTile() after 1000 milliseconds at the end of the unpeekTile() function:
function peekTile() {
var peekAnimation = WinJS.UI.Animation.createPeekAnimation([tile1, tile2]);
// Reposition tiles to their desired post-animation position
tile1.style.top = "-150px";
tile2.style.top = "-150px";
peekAnimation.execute();
}
function unpeekTile() {
/* your code here */
setTimeout(peekTile, 1000);
}
setInterval(unpeekTile, 1000);
Check out the fiddle
var animation = (function () {
var peekInterval, unpeekInterval, delay;
return {
start: function (ip) {
delay = ip;
peekInterval = setTimeout(animation.peekTile, delay);
},
peekTile: function () {
//Your Code goes here
console.log('peek');
unpeekInterval = setTimeout(animation.unpeekTile, delay);
},
unpeekTile: function () {
//Your Code goes here
console.log('unpeek');
peekInterval = setTimeout(animation.peekTile, delay);
},
stop: function () {
clearTimeout(peekInterval);
clearTimeout(unpeekInterval);
}
}
})();
animation.start(1000);
// To stop
setTimeout(animation.stop, 3000);
I can't use this instead of animation.peekTile as setTimeout executes in global scope