Finish script on original document.title? - javascript

The problem I have is that this script finishes on the flash title what would I have to change so that this script finishes with the original document title. Hopefully you understand what I'm trying to achieve.
(function () {
var original = document.title;
var timeout;
window.flashTitle = function (newMsg, howManyTimes) {
function step() {
document.title = (document.title == original) ? newMsg : original;
if (--howManyTimes > 0) {
timeout = setTimeout(step, 1000);
};
};
howManyTimes = parseInt(howManyTimes);
if (isNaN(howManyTimes)) {
howManyTimes = 5;
};
cancelFlashTitle(timeout);
step();
};
window.cancelFlashTitle = function () {
clearTimeout(timeout);
document.title = original;
};
}());
flashTitle("New Notification");

You need to make sure that the howManyTimes var is an even number, if it is an odd number, it will end on the newMsg:
(function () {
var original = document.title;
var timeout;
window.flashTitle = function (newMsg, howManyTimes) {
if (isNaN(howManyTimes)) {
howManyTimes = 5;
};
howManyTimes = (howManyTimes % 2 == 0) ? howManyTimes : howManyTimes + 1;
function step() {
document.title = (document.title == original) ? newMsg : original;
if (--howManyTimes > 0) {
timeout = setTimeout(step, 1000);
};
};
howManyTimes = parseInt(howManyTimes);
cancelFlashTitle(timeout);
step();
};
window.cancelFlashTitle = function () {
clearTimeout(timeout);
document.title = original;
};
}());
flashTitle("New Notification");
EDIT - fixed small error

Related

Debounce return timer

I don't understand the principle of operation. I have a code in which I have to create a delay of 2 seconds during the twist but during the delay script should not work using the debounce script but for some reason it always returns some timer and not an answer from function that the debounce script accepts
function debounce(f, ms) {
let timer = null;
return function(...args) {
const onComplete = () => {
f.apply(this, args);
timer = null;
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(onComplete, ms);
};
}
var delay = false;
$('.window').on('mousewheel', function(event) {
var pozition = $(document).scrollTop();
var block2 = $(".main_step").offset().top
var elemId = $(this).attr('id'),
scrollDir = event.deltaY;
var indicatorL = $(".indicator_main").data("counter");
if (elemId == 'steps' && scrollDir < 0 && delay === false) {
if (indicatorL != "4") {
$("#sli-" + indicatorL).css("display", "none");
indicatorL = indicatorL + 1;
$("#sli-" + indicatorL).css("display", "block");
$(".indicator_main").data("counter", indicatorL);
$(".indicator_main").animate({
"left": "+=25%"
}, "slow");
$(".indicator_num").text("0" + indicatorL);
$(".step_nr").text("0" + indicatorL);
}
}
delay = true;
var f = function() {
var delay = false;
return delay;
};
delay = debounce(f, 2000);
console.log(delay);
});

javascript How to pause/resume function?

How to pause/resume odometer (so that it pauses/resumes)? I want to be able to pause/resume odometer respectively each time I click .pause-resume button.
This is my code:
https://jsfiddle.net/aht87opr/27/
$('button').click(function() {
var currentvalue = myOdometer.get();
$('#value').text(currentvalue);
});
use setInterval function
var n = 0,
timerID;
var myOdometer;
var div = document.getElementById("odometerDiv");
myOdometer = new Odometer(div, {
value: n,
digits: 6,
tenths: true
});
myOdometer.set(0);
function startcounting() {
timerID = setInterval(function() {
n = n + 0.01
myOdometer.set(n);
}, 200);
}
//]]>
startcounting();
var started = true;
$('button').click(function() {
if (started)
clearTimeout(timerID);
else
startcounting();
started = !started;
var currentvalue = myOdometer.get();
$('#value').text(currentvalue);
});
fiddle
var n = 0;
var timer;
var myOdometer;
function startcounting () {
var div = document.getElementById("odometerDiv");
myOdometer = new Odometer(div, {value: n, digits: 6, tenths: true});
myOdometer.set(0);
update();
}
function update () {
timer = setInterval(function() {
n = n + 0.01
myOdometer.set(n);}, 200);}
startcounting();
var state = true;
$('button').click(function() {
if (state)
clearTimeout(timer);
else
update();
state = !state;
var currentvalue = myOdometer.get();
$('#value').text(currentvalue);
});

How to pass unspecified number of parameters to setInterval

I need to create an interval wrapper to track if it has been cleared.
The number of parameters to pass to the interval callback should be variable. So this is the code (not working) I implemented to test it:
function MyInterval() {
var id = setInterval.apply(this, arguments); // NOT VALID!!
this.cleared = false;
this.clear = function() {
this.cleared = true;
clearInterval(id);
};
}
var x = 2;
var y = 3;
var fn = function() {
x = x + y;
console.log(x);
};
var interval = new MyInterval(fn, 5000, x, y);
Within the call to setInterval, this must refer to the global object, so instead of this, you want window in your constructor:
var id = setInterval.apply(window, arguments);
// here -------------------^
(or in loose mode you could use undefined or null.)
Then it works, at least on browsers where setInterval is a real JavaScript function and therefore has apply:
function MyInterval() {
var id = setInterval.apply(window, arguments);
this.cleared = false;
this.clear = function() {
this.cleared = true;
clearInterval(id);
};
}
var x = 2;
var y = 3;
var fn = function() {
x = x + y;
log(x);
};
var interval = new MyInterval(fn, 500, x, y);
setTimeout(function() {
interval.clear();
}, 3000);
function log(msg) {
var p = document.createElement('p');
p.appendChild(document.createTextNode(msg));
document.body.appendChild(p);
}
Note, though, that host-provided functions are only required to be callable, they are not required to inherit from Function.prototype and so they're not required/guaranteed to have apply. Modern browsers ensure they do, but earlier ones (IE8, for instance) did not. I can't speak to how well-supported apply is on setInterval.
If you need to support browsers that may not have it, just to use your own function:
function MyInterval(handler, interval) {
var args = Array.prototype.slice.call(arguments, 2);
var tick = function() {
handler.apply(undefined, args);
};
var id = setInterval(tick, interval);
this.cleared = false;
this.clear = function() {
this.cleared = true;
clearInterval(id);
};
}
This also has the advantage that it works even on browsers that don't support additional args on setInterval (fairly old ones).
Example:
function MyInterval(handler, interval) {
var args = Array.prototype.slice.call(arguments, 2);
var tick = function() {
handler.apply(undefined, args);
};
var id = setInterval(tick, interval);
this.cleared = false;
this.clear = function() {
this.cleared = true;
clearInterval(id);
};
}
var x = 2;
var y = 3;
var fn = function() {
x = x + y;
log(x);
};
var interval = new MyInterval(fn, 500, x, y);
setTimeout(function() {
interval.clear();
}, 3000);
function log(msg) {
var p = document.createElement('p');
p.appendChild(document.createTextNode(msg));
document.body.appendChild(p);
}
You might be tempted to use the new ES2015 spread operator:
var id = setInterval(...arguments);
...but note that if you transpile (and right now you'd have to), it ends up being an apply call, and so you have the issue of whether apply is supported.
I suggest that you pass an "options" parameter to your timeout.
var MyInterval = (function(window) {
return function(callbackFn, timeout, options) {
var id = setInterval.apply(window, arguments);
this.cleared = false;
this.clear = function() {
this.cleared = true;
clearInterval(id);
};
}
}(window));
var fn = function(opts) {
opts.x += opts.y;
console.log('x = ', opts.x);
};
var opts = {
x: 2,
y: 3
};
var ms = 5000;
var interval = new MyInterval(fn, ms, opts);
// Bootstrap a custom logger. :)
console.log = function() {
var logger = document.getElementById('logger');
var el = document.createElement('LI');
el.innerHTML = [].join.call(arguments, ' ');
logger.appendChild(el);
logger.scrollTop = logger.scrollHeight;
}
body{background:#7F7F7F;}h1{background:#D7D7D7;margin-bottom:0;padding:0.15em;border-bottom:thin solid #AAA;color:#444}#logger{height:120px;margin-top:0;margin-left:0;padding-left:0;overflow:scroll;max-width:100%!important;overflow-x:hidden!important;font-family:monospace;background:#CCC}#logger li{list-style:none;counter-increment:step-counter;padding:.1em;border-bottom:thin solid #E7E7E7;background:#FFF}#logger li:nth-child(odd){background:#F7F7F7}#logger li::before{content:counter(step-counter);display:inline-block;width:1.4em;margin-right:.5em;padding:.25em .75em;font-size:1em;text-align:right;background-color:#E7E7E7;color:#6A6A6A;font-weight:700}
<h1>Custom HTML Logger</h1><ol id="logger"></ol>
I created a utility function rather than a constructor to solve your issue.
function Wrapper(delay) {
var isCleared,
intervalId,
intervalDelay = delay || 5e3; // default delay of 5 sec
function clear() {
if (!isCleared) {
console.log('clearing interval');
isCleared = true;
clearInterval(intervalId);
}
}
function setUpInterval(callback){
var params = [].slice.call(arguments, 1);
if (!callback) {
throw new Error('Callback for interval expected');
}
params.unshift(intervalDelay);
params.unshift(callback);
intervalId = setInterval.apply(null, params);
}
return {
setUp : setUpInterval,
clear : clear
}
}
function intervalCallback() {
console.log([].slice.call(arguments).join(','));
}
var wrapper = Wrapper(1e3); // create wrapper with delay for interval
console.log('test case 1');
wrapper.setUp(intervalCallback, 'params', 'to', 'callback');
// call clear interval after 10sec
setTimeout(function() {
wrapper.clear();
}, 10e3);
Hope this helps.

Change images with different timeinterval using Js or jquery

How to change images with different time interval in a single div using CSS3, JavaScript or jQuery. At the last time interval should be cleared.
You can try this http://codepen.io/jammer99/pen/PNErKp
var timing = [1000, 2000, 500, 300, 800],
timeouts
function runinterval() {
timeouts = setTimeout(function() {
clearTimeout(timeouts);
timing.shift();
$(".imgholder").css("background-image", "url(https://unsplash.it/100/100/?random&i=" + new Date().getTime() + ")")
if (timing.length != 0)
runinterval();
}, timing[0])
}
runinterval();
Maybe something like this can help you.
var setTimer = (function(){
function setTimer( options ){
this.timings = options.timings;
this.element = options.element;
this.images = options.images;
this.index = -1;
this.interval = false;
this.init();
}
setTimer.prototype.init = function(){
this.image_ = document.createElement('img');
this.image_.setAttribute('class','slider-image');
this.element.appendChild( this.image_ );
this.set();
};
setTimer.prototype.set = function(){
if( this.interval && false !== this.interval ){
clearTimeout( this.interval );
}
if( this.index >= this.images.length-1 ){ this.index = 0; }
else{ this.index++; }
var timing = this.timings[this.index];
console.log(this.index);
console.log(timing);
this.interval = (function(_this){
return setTimeout(function(){
_this.switch_image();
},timing);
})(this);
};
setTimer.prototype.switch_image = function(){
var index = this.index;
console.log('switching image to '+this.images[index]);
this.image_.setAttribute('src',this.images[index]);
this.set();
}
return setTimer;
})();
setTimeout(function(){
var options = {
timings: [10,1000,2000],
images : [ 'url1','url2','url3'],
element: document.getElementById('your-image-container-id')
};
new setTimer(options);
},1000);

how to clear all javascript Timeouts?

i have a loop function that in first 5 seconds it runs social1() and in second 5 seconds it runs social2() then loop ...
i have 2 hover functions too
i need clear all active timeouts because when i hover on images (.social1 & .social2), i can see that multiple timeouts are running
how to fix this?
function social1() {
$('.social1').fadeTo(500, 1);
$('.social2').fadeTo(500, 0.5);
timeout = setTimeout(function() {
social2();
}, 5000);
}
function social2() {
$('.social1').fadeTo(500, 0.5);
$('.social2').fadeTo(500, 1);
timeout = setTimeout(function() {
social1();
}, 5000);
}
$(document).ready(function ()
{
social1();
$('.social1').hover(
function () {
window.clearTimeout(timeout);
social1();
},
function () {
timeout = setTimeout(function() {
social2();
}, 5000);
}
);
$('.social2').hover(
function () {
window.clearTimeout(timeout);
social2();
},
function () {
timeout = setTimeout(function() {
social1();
}, 5000);
}
);
__EDIT__
To manage a collection of timeouts (and intervals), you could use following snippet.
This will allow to clear any timeouts or intervals set anywhere in code, although, you have to set this snippet before setting any timeout or interval. Basically, before processing any javascript code or external script which uses timeout/interval.
JS:
;(function () {
window.timeouts = {},
window.intervals = {},
window.osetTimeout = window.setTimeout,
window.osetInterval = window.setInterval,
window.oclearTimeout = window.clearTimeout,
window.oclearInterval = window.clearInterval,
window.setTimeout = function () {
var args = _parseArgs('timeouts', arguments),
timeout = window.osetTimeout.apply(this, args.args);
window.timeouts[args.ns].push(timeout);
return timeout;
},
window.setInterval = function () {
var args = _parseArgs('intervals', arguments),
interval = window.osetInterval.apply(this, args.args);
window.intervals[args.ns].push(interval);
return interval;
},
window.clearTimeout = function () {
_removeTimer('timeouts', arguments);
},
window.clearInterval = function () {
_removeTimer('intervals', arguments);
},
window.clearAllTimeout = function () {
_clearAllTimer('timeouts', arguments[0]);
},
window.clearAllInterval = function () {
_clearAllTimer('intervals', arguments[0]);
};
function _parseArgs(type, args) {
var ns = typeof args[0] === "function" ? "no_ns" : args[0];
if (ns !== "no_ns")[].splice.call(args, 0, 1);
if (!window[type][ns]) window[type][ns] = [];
return {
ns: ns,
args: args
};
}
function _removeTimer(type, args) {
var fnToCall = type === "timeouts" ? "oclearTimeout" : "oclearInterval",
timerId = args[0];
window[fnToCall].apply(this, args);
for (var k in window[type]) {
for (var i = 0, z = window[type][k].length; i < z; i++) {
if (window[type][k][i] === timerId) {
window[type][k].splice(i, 1);
if (!window[type][k].length) delete window[type][k];
return;
}
}
}
}
function _clearAllTimer(type, ns) {
var timersToClear = ns ? window[type][ns] : (function () {
var timers = [];
for (var k in window[type]) {
timers = timers.concat(window[type][k]);
}
return timers;
}());
for (var i = 0, z = timersToClear.length; i < z; i++) {
_removeTimer(type, [timersToClear[i]]);
}
}
}());
How to use it:
Set timeout(s)/interval(s) as usual:
var test1 = setTimeout(function(){/**/, 1000);
var test2 = setTimeout(function(){/**/, 1000);
Then you could use to clear both:
clearAllTimeout(); // clearAllInterval(); for intervals
This will clear both timeouts (test1 & test2)
You can use some namespaces to clear only specific timers, e.g:
// first (optional) parameter for setTimeout/setInterval is namespace
var test1 = setTimeout('myNamespace', function(){/**/, 1000); // 'myNamespace' is current namespace used for test1 timeout
var test2 = setTimeout(function(){/**/, 1000); // no namespace used for test2 timeout
Again, clearAllTimeout(); will clear both timeouts. To clear only namespaced one, you can use:
clearAllTimeout('myNamespace'); // clearAllInterval('myNamespace'); for namespaced intervals
This will clear only test1 timeout
You could for some reason wish to delete non namespaced timeouts only. You could then use:
clearAllTimeout('no_ns'); // clearAllInterval('no_ns'); for non namespaced intervals only
This will clear only test2 timeout in this example
See jsFiddle DEMO
__END of EDIT__
Old post specific to opening question here:
You could try that:
var timeouts = [];
timeouts.push(setTimeout(function() {
social2();
}, 5000));
timeouts.push(setTimeout(function() {
social1();
}, 5000));
//etc...
function clearAllTimeouts(){
for(var i = 0, z = timeouts.length; i < z; i++)
clearTimeout(timeouts[i]);
timeouts = [];
}
UPDATED following David Thomas comment
var timeouts = {'social' : [], 'antisocial' : []};
//a social timeout
timeouts.social.push(setTimeout(function() {
social1();
}, 5000));
//an anti-social timeout
timeouts.antisocial.push(setTimeout(function() {
antisocial1();
}, 5000));
function clearTimeouts(namespace){
for(var i = 0, z = timeouts[namespace].length; i < z; i++)
clearTimeout(timeouts[namespace][i]);
timeouts[namespace] = [];
}
//usage e.g
clearTimeouts("social");
//Incase if you are looking for full fledged code
var dict = {};
function checkForIntervals(id){
var index = index;
var result = findOrAddProperty(id);
if(result.length != 0){
clearTimeoutsFor(id);
}
dict[id].push(setTimeout(function(){alertFunc(id,index);}, 60000));
};
// to clear specific area timeout
function clearTimeoutsFor(namespace){
for(var i = 0, z = dict[namespace].length; i < z; i++)
clearTimeout(dict[namespace][i]);
dict[namespace] = [];
}
to clear all timeouts
function clearAllTimeOuts(){
for (key in dict) {
for(var i = 0, z = dict[key].length; i < z; i++)
clearTimeout(dict[key][i]);
dict[key] =[];
}
};
function findOrAddProperty(str){
var temp = [];
for (key in dict) {
if(key == str){
if (dict.hasOwnProperty(key)) {
temp = dict[key];
break;
}
}
}
if(temp.length == 0){
dict[str] = [];
}
return temp;
};
function alertFunc(id,index) {
jQuery(document).ready(function($) {
do the ajax call here after 1 min
});
};

Categories

Resources