javascript How to pause/resume function? - javascript

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

Related

How to stop javascript counter at specific number

I have this javascript code for tampermonkey that works on Amazon. What it does is just counts up your gift card balance and makes it look like I am getting money. I want to know if it is possible to make it stop at a specific number.
var oof = document.getElementById("gc-ui-balance-gc-balance-value");
var lastCount = localStorage.getItem("lastCount");
oof.innerText = '$' + lastCount || "$10000";
function animateValue(id) {
var obj = document.getElementById(id);
var current = parseInt(localStorage.getItem("lastCount")) || 10000;
setInterval(function () {
var nextCount = current++;
localStorage.setItem("lastCount", nextCount);
obj.innerText = '$' + nextCount;
}, 0.1);
}
animateValue('gc-ui-balance-gc-balance-value')
Use clearInterval inside your setInterval callback so each time the callback is called, you can check if the new count has reached your threshold and clear the timer if it does.
If you check the value outside of the callback, the logic won't be called at each count increment.
function animateValue(id) {
var obj = document.getElementById(id);
var current = parseInt(localStorage.getItem("lastCount")) || 10000;
var interval = null;
var maxCount = 1000;
var callback = function() {
var nextCount = current++;
if (nextCount === maxCount) {
clearInterval(interval);
}
localStorage.setItem("lastCount", nextCount);
obj.innerText = '$' + nextCount;
}
interval = setInterval(callback, 0.1);
}
Here is a demo:
let current = 0;
let interval = null;
const callback = () => {
let nextCount = current++;
console.log(nextCount);
if (nextCount === 5) {
clearInterval(interval);
}
}
interval = setInterval(callback, 100);
May be by clearing the interval when current reaches to a specific value like this
function animateValue(id) {
// rest of the code
let interval = setInterval(function() {
var nextCount = current++;
localStorage.setItem("lastCount", nextCount);
obj.innerText = '$' + nextCount;
}, 0.1);
if (current === requiredVal) {
clearInterval(interval)
}
return current;
}

Finish script on original document.title?

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

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>

How to Pause the timer on window blur and resume the timer on window focus event?

Thanks for seeing my question.
I am using wp-pro-quiz plugin for quiz. I want to know that how can I pause the timer if the window is not in focus or is blur and resume it when it is back to focus.?
My code:
I get reset when it get focused
var timelimit = (function () {
var _counter = config.timelimit;
var _intervalId = 0;
var instance = {};
instance.stop = function () {
if (_counter) {
window.clearInterval(_intervalId);
globalElements.timelimit.hide();
}
};
instance.start = function () {
var x;
var beforeTime;
if (!_counter)
return;
var $timeText = globalElements.timelimit.find('span').text(plugin.methode.parseTime(_counter));
var $timeDiv = globalElements.timelimit.find('.wpProQuiz_progress');
globalElements.timelimit.show();
$.winFocus(function (event) {
console.log("Blur\t\t", event);
},
function (event) {
console.log("Focus\t\t", event);
x = _counter * 1000;
beforeTime = +new Date();
});
_intervalId = window.setInterval(function () {
var diff = (+new Date() - beforeTime);
var elapsedTime = x - diff;
if (diff >= 500) {
$timeText.text(plugin.methode.parseTime(Math.ceil(elapsedTime / 1000)));
}
$timeDiv.css('width', (elapsedTime / x * 100) + '%');
if (elapsedTime <= 0) {
instance.stop();
plugin.methode.finishQuiz(true);
}
}, 16);
};
return instance;
})();
Use this wrapper function to pause, resume your timeout.
var Timer;
Timer = function(callback, delay) {
var remaining, start, timerId;
timerId = void 0;
start = void 0;
remaining = delay;
this.pause = function() {
window.clearTimeout(timerId);
remaining -= new Date - start;
};
this.resume = function() {
start = new Date;
window.clearTimeout(timerId);
timerId = window.setTimeout(callback, remaining);
};
this.resume();
};
Intialize it like this, timer = new Timer("callback_function_here", 45000)
In this case total time is 45 seconds for the callback and upon event triggers(blur or focus in your case) it will pause or resume the timer accordingly.
timer.pause() //pause the timer
timer.resume() //resume the timer
P.S - Use this function as per the logic of your code. You will have to make the timer calls accordingly in your code
I did it this way:
var time0 ; var setTimeout_Int; var focused = true; var resume_Fun ;
var addTime =0; var addTimeDiff =0;
window.onfocus = function() {
focused = true;
var d = new Date();
addTimeDiff = addTimeDiff +( d.getTime() - addTime );
resume_Fun();
};
window.onblur = function()
{
focused = false;
};
function init()
{
var d = new Date();
time0 = d.getTime();
setTimeout_Int = setTimeout(update, 1000 )
}
function update()
{
clearTimeout(setTimeout_Int);
var d = new Date();
if(focused)
{
if(d.getTime() -(time0+addTimeDiff) < 20000)
{
setTimeout_Int= setTimeout(update, 1000 )
}
}
else
{
addTime = d.getTime();
resume_Fun = update;
}
}
init();

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