How to incorporate delay on a function? - javascript

I'm trying to implement a delay on a function. Should I wrap the function inside a delay function? Or can I somehow add more code, so that the animation doesn't start before 5 sec after page load?
var typeThis = "blablablabla";
var displayText = "";
function type(fullString, typedSoFar) {
if (fullString.length != typedSoFar.length) {
typedSoFar = fullString.substring(0, typedSoFar.length + 1);
document.getElementById("logoType").innerText = typedSoFar;
setTimeout(function() {
type(fullString, typedSoFar)
}, 150);
}
}
document.getElementById("logoType").innerHtml = typeThis;
var element = document.createElement('h2');
element.innerHTML = typeThis;
typeThis = element.textContent;
type(typeThis, displayText);
<a class="navbar-brand" id="topper" href="#"><p id="logoType"></p></a>

I think what you are looking for is setTimeout.
window.setTimeout(function () {
type(typeThis, displayText);
}, 5000);
You can also add that to a listener to know when the window has finished loading:
window.addEventListener('load', function () {
window.setTimeout(function () {
type(typeThis, displayText);
}, 5000);
});
A full example:
var typeThis = "blablablabla";
var displayText = "";
function type(fullString, typedSoFar) {
if (fullString.length != typedSoFar.length) {
typedSoFar = fullString.substring(0, typedSoFar.length + 1);
document.getElementById("logoType").innerText = typedSoFar;
setTimeout(function() {
type(fullString, typedSoFar)
}, 150);
}
}
document.getElementById("logoType").innerHtml = typeThis;
var element = document.createElement('h2');
element.innerHTML = typeThis;
typeThis = element.textContent;
window.addEventListener('load', function() {
window.setTimeout(function() {
type(typeThis, displayText);
}, 5000);
});
Waiting 5 seconds...
<a class="navbar-brand" id="topper" href="#"><p id="logoType"></p></a>

Your best bet is not going to be adding more code to delay, but wrap this all in a Timeout: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

Use setTimeout() like so:
var timeoutID;
function delayedAlert() {
timeoutID = window.setTimeout(slowAlert, 2000);
}
function slowAlert() {
alert("That was really slow!");
}
function clearAlert() {
window.clearTimeout(timeoutID);
}
Source: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

Related

clearInterval/run function only once not working

The function and console.log("a") keep firing when I repeatedly move out of trw and moving back in, it just doesn't stop. How do I make the function stop after I've called onblur once?
var Hello = false;
var looper = setInterval(function() {
if (!Hello) {
trw.onblur = function() {
console.log("a");
clearInterval(looper);
Hello = true;
}
}
}, 1);
Don't use listener inside the interval better use outside
var Hello = false;
var looper = setInterval(function() {
if (!Hello) {
console.log("a");
}
}, 1);
document.getElementById('trw').onblur = function() {
console.log("stopped");
clearInterval(looper);
Hello = true;
}
<input type="text" id="trw">

Resume a function after clearInterval

I have this code:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0;
var timer = setInterval(function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
clearInterval(timer);
}
});
$el.mouseout({
timer;
});
});
I want to suspend the function on mouseover and resume it on mouse out but I cant get the latter right. How can I resume it?
Thank you.
There are two ways:
Set a flag that the function being called by the interval checks, and have the function not do anything if it's "suspended."
Start the interval again via a new setInterval call. Note that the old timer value cannot be used for this, you need to pass in the code again.
Example of #1:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0,
suspend = false; // The flag
var timer = setInterval(function() {
if (!suspend) { // Check it
$el.removeClass("current").eq(++c % tot).addClass("current");
}
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
suspend = true; // Set it
},
mouseleave: function(e) {
suspend = false; // Clear it
}
});
});
Example of #2:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0,
timer = 0;
// Move this to a reusable function
var intervalHandler = function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
};
// Probably best to encapsulate the logic for starting it rather
// than repeating that logic
var startInterval = function() {
timer = setInterval(intervalHandler, 3000);
};
// Initial timer
startInterval();
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
clearInterval(timer); // Stop it
}
mouseleave: function(e) {
startInterval(); // Start it
}
});
});
Checkout these prototypes:
//Initializable
function Initializable(params) {
this.initialize = function(key, def, private) {
if (def !== undefined) {
(!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
}
};
}
function PeriodicJobHandler(params) {
Initializable.call(this, params);
this.initialize("timeout", 1000, true);
var getTimeout = function() {
return params.timeout;
};
var jobs = [];
function Job(params) {
//expects params.job() function
Initializable.call(this, params);
this.initialize("timeout", getTimeout(), true);
this.initialize("instant", false);
var intervalID = undefined;
this.start = function() {
if (intervalID !== undefined) {
return;
}
if (this.instant) {
params.job(true);
}
intervalID = setInterval(function() {
params.job(false);
}, params.timeout);
};
this.stop = function() {
clearInterval(intervalID);
intervalID = undefined;
};
}
this.addJob = function(params) {
jobs.push(new Job(params));
return jobs.length - 1;
};
this.removeJob = function(index) {
jobs[index].stop();
jobs.splice(index, 1);
};
this.startJob = function(index) {
jobs[index].start();
};
this.stopJob = function(index) {
jobs[index].stop();
};
}
Initializable simplifies member initialization, while PeriodicJobHandler is able to manage jobs in a periodic fashion. Now, let's use it practically:
var pjh = new PeriodicJobHandler({});
//It will run once/second. If you want to change the interval time, just define the timeout property in the object passed to addJob
var jobIndex = pjh.addJob({
instant: true,
job: function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}
});
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0;
var timer = setInterval(function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
jobIndex.stop();
}
});
$el.mouseout({
jobIndex.start();
});
});
With Javascript, it is much easy and efficient.
You can change the interval in setInterval function.
It is checking whether suspend variable is false or true, here suspend variable is setting to true, if mouseEnter function is called and set to false if mouseLeave function is called.
var displayMsg = document.getElementById('msg').innerHTML;
var i = 0;
var suspend = false;
var sequence = setInterval(update, 100);
function update() {
if (suspend == false) {
var dispalyedMsg = '';
dispalyedMsg = displayMsg.substring(i, displayMsg.length);
dispalyedMsg += ' ';
dispalyedMsg += displayMsg.substring(0, i);
document.getElementById('msg').innerHTML = dispalyedMsg;
i++;
if (i > displayMsg.length) {
i = 0;
}
}
}
document.getElementById('msg').addEventListener('mouseenter', mouseEnter);
document.getElementById('msg').addEventListener('mouseleave', mouseLeave);
function mouseEnter() {
suspend = true;
}
function mouseLeave() {
suspend = false;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#msg {
width: 680px;
height: 100px;
border: 1px solid #ccc;
padding-left: 15px;
}
</style>
</head>
<body>
<div id="msg">
Today is only 15% discount. Hurry up to grab. Sale will end sooooooooooooon!!!!
</div>
<div id="output"></div>
<script src="marquee.js"></script>
</body>
</html>

javascript autoreload in infinite loop with time left till next reload

i need a JavaScript, that relaods a page every 30 seconds, and will show how much time there is until next reload at the ID time-to-update, Example:
<p>Refreshing in <span id="time-to-update" class="light-blue"></span> seconds.</p>
i also need it to repeat itself infinitely.
thank you for reading, i hope it helps not me but everyone else, and a real big thank you if you could make this script.
(function() {
var el = document.getElementById('time-to-update');
var count = 30;
setInterval(function() {
count -= 1;
el.innerHTML = count;
if (count == 0) {
location.reload();
}
}, 1000);
})();
A variation that uses setTimeout rather than setInterval, and uses the more cross-browser secure document.location.reload(true);.
var timer = 30;
var el = document.getElementById('time-to-update');
(function loop(el) {
if (timer > 0) {
el.innerHTML = timer;
timer -= 1;
setTimeout(function () { loop(el); }, 1000);
} else {
document.location.reload(true);
}
}(el));
http://jsfiddle.net/zGGEH/1/
var timer = {
interval: null,
seconds: 30,
start: function () {
var self = this,
el = document.getElementById('time-to-update');
el.innerText = this.seconds; // Output initial value
this.interval = setInterval(function () {
self.seconds--;
if (self.seconds == 0)
window.location.reload();
el.innerText = self.seconds;
}, 1000);
},
stop: function () {
window.clearInterval(this.interval)
}
}
timer.start();

check if the page is on the top of the window

I need to check if an html page is on the top of the window or not.
So, i am using this code:
$(window).scroll(function(){
a = ($(window).scrollTop());
if (a>0) {
alert('page not in top');
}
});
But this is not working as expected because the event should be fired only when the user stops the scroll action. Any idea?
Try this:
var timer = null;
$(window).addEventListener('scroll', function() {
if(timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(function() {
// do something
}, 150);
}, false);
Or this one:
var timer;
$(window).bind('scroll',function () {
clearTimeout(timer);
timer = setTimeout( refresh , 150 );
});
var refresh = function () {
// do stuff
console.log('Stopped Scrolling');
};
Use setTimeout:
var timeout;
$(window).scroll(function() {
clearTimeout(timeout);
timeout = setTimeout(function(){
a = $(window).scrollTop();
if ( a > 0 ) {
alert('page not in top');
}
}, 100);
});

clearInterval(); then call interval again

I have a setInterval function
var auto_refresh = setInterval(function () {
if ($('#addNewJuicebox:visible')) {
clearInterval();
}
//rest of function
}, 8000); // refresh every 5000 milliseconds
I want to call the setInterval later again, what's the best way to do that?
Try breaking your code up into the storage of the interval and the setting.
var auto_refresh = "";
function startRefresh() {
if (auto_refresh != "") {
// already set
return;
}
auto_refresh = setInterval(function() {
if ($('#addNewJuicebox:visible')) {
clearInterval(auto_refresh);
auto_refresh = "";
}
}, 8000);
}
Added a jsfiddle example for demonstrating starting and stopping an interval
http://jsfiddle.net/Jf8PT/
This may be what you're looking for
Function TaskRunner(run, interval) {
this._taskId = null;
this._run = run;
this._interval = interval
}
TaskRunner.prototype.start = function(){
if (this._taskId) {
return; // Already running
}
this._taskId = setInterval(this._taskId, this._interval);
}
TaskRunner.prototype.stop = function(){
if (!this._taskId) {
return; // Not running
}
clearInterval(this._taskId);
this._taskId = null;
}
var task = new TaskRunner(
function(){
if ($('#addNewJuicebox:visible')) {
task.stop();
}
// Do the update
}, 5000);
Now you can call `task.start()` from anywhere in your code to restart it.
clearInterval takes in a reference to the timer that you want to clear, you need to pass that in to it:
var auto_refresh = null;
var refresh = function () {
if ($('#addNewJuicebox').is(':visible')) {
clearInterval(auto_refresh);
auto_refresh = null;
}
};
var start_refreshing = function() {
if(auto_refresh != null) return;
auto_refresh = setInterval(refresh, 8000);
};
start_refreshing();
Maybe you just want to use setTimeout() instead, so that you have the control you're looking for?

Categories

Resources