so i'm new to javascript and jquery. Need some help on how to run the 2nd function after the 1st one has completed?
The first function is a progress bar and the second one is a form that i want to fade in after the progressbar animation completed.
The script:
$(function() {
var msecsPerUpdate = 1000 / 60; // # of milliseconds between updates, this gives 60fps
var progress = $('progress');
var duration = 1; // secs to animate for
var interval = progress.attr('max') / (duration * 1000 / msecsPerUpdate);
var animator = function() {
progress.val(progress.val() + interval);
if (progress.val() + interval < progress.attr('max')) {
setTimeout(animator, msecsPerUpdate);
} else {
progress.val(progress.attr('max'));
}
}
$('a#forgot').click(animator);
});
$(function(e) {
e.preventDefault();
$('generator#forgot').css('bottom', '5px');
$(this).fadeOut('medium', function() {
$('a#back').fadeIn();
});
});
Thanks in advance!
I'd add a callback function to your animator function to make it look like this:
var animator = function(callback) {
progress.val(progress.val() + interval);
if (progress.val() + interval < progress.attr('max')) {
setTimeout(animator, msecsPerUpdate);
} else {
progress.val(progress.attr('max'));
callback();
}
}
Then you can call it like this:
$('a#forgot').click(function() {
animator(function() {
console.log('this runs after your animation has completed');
});
});
Note: this is a simplified code-snippet without params or error handling, which you might wanna add.
Related
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>
I got this code from: Jquery: mousedown effect (while left click is held down)
It is behaving that if I am holding the button in every 50ms it will do something.
var timeout = 0;
$('#button_add').mousedown(function () {
timeout = setInterval(function () {
value_of_something ++;
}, 50);
return false;
});
});
But what I want is to execute this part after holding down the button by 1 second and it will continuously do the action 50ms.
As I said you need to use setTimeout()
var timeout = 0;
$('#button_add').mousedown(function () {
setTimeout(function(){
timeout = setInterval(function () {
value_of_something ++;
}, 50);
} , 1000);
return false;
});
Jsfiddle
Please use this code... You have to clearTimeout when user mouseup :
var timeout = 0;
$('#button_add').mousedown(function() {
oneSecondTimer = setTimeout(function() {
timeout = setInterval(function() {
value_of_something++;
}, 50);
}, 1000);
return false;
});
$("#button_add").mouseup(function() {
clearTimeout(oneSecondTimer);
});
I'm working on a little "web app" for a quiz.
Each slide has got a certain amount of time to be answered (or 0 to infinite time).
I find JS here to do the countdown:
function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {},
counterEnd = options.onCounterEnd || function () {};
function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds--;
}
this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
};
this.stop = function () {
clearInterval(timer);
};
}
var myCounter = new Countdown({
seconds: timetogo, // number of seconds to count down
onUpdateStatus: function (sec) {
elapsed = timetogo - sec;
$('.progress-bar').width(((elapsed / timetogo) * 100) + "%");
}, // callback for each second
onCounterEnd: function () {
//alert('counter ended!');
} // final action
});
myCounter.start();
I made a jsfiddle here :
https://jsfiddle.net/mitchum/kz2400cc/2/
But i am having trouble when you go to the next slide, the progress bar "bump".
after looking into "live source panel from chrome" I saw it's like the first "counter" is not stopped and still runs.
Do you have any tips or hint to help me to solve my bug ?
Thanks
You must pay attention to the scope of the variables. I change the "var myCounter" under document ready in "var myCounterFirst". Check the updated JSFiddle.
var timetogoFirst = $('.current').attr("data-time");
var myCounterFirst = new Countdown({
seconds: timetogoFirst, // number of seconds to count down
onUpdateStatus: function (sec) {
elapsed = timetogoFirst - sec;
$('.progress-bar').width(((elapsed / timetogoFirst) * 100) + "%");
}, // callback for each second
onCounterEnd: function () {
alert('counter ended!');
} // final action
});
myCounterFirst.start();
I know that most probably such question has been requested several times but I have a need to show a popup or message or whatelse when a javascript function is triggered and hide it at the end.
See this simple js fiddle
That's the HTML code:
<div id='message'>Default message</div>
<input type='button' onclick='Run();' value='start'>
the div 'message' has to contain a simple text like "running" or "please wait" or ...
That's the JS function that took (delay) 3 seconds:
function Run() {
var delay = 3000; //-- 3 seconds
$( '#message' ).text('Please wait ' + delay + ' seconds...');
var start = new Date().getTime();
while (true) {
current = new Date().getTime();
if ( (start + delay) < current) {
break;
}
}
$( '#message' ).text('Done');
}
The expected behaviour is that the '#message' div contains "Please wait 3 seconds..." before to enter in the loop and "Done" string only at the end.
But that's not.
Can anyone explain me (most probably "again") why or suggest a link where to find an answer?
The JS event loop is too busy running while (true) {} to handle a DOM repaint.
Use setInterval, setTimeout, or requestAnimationFrame to trigger the next test of the time instead of a loop.
function Run() {
var delay = 3000; //-- 3 seconds
$( '#message' ).text('Please wait ' + delay + ' seconds...');
var start = new Date().getTime();
setTimeout(whenDelayIsOver, 50);
function whenDelayIsOver() {
if ( (start + delay) < current) {
$( '#message' ).text('Done');
} else {
setTimeout(whenDelayIsOver, 50);
}
}
}
… or just use setTimeout in the first place.
function Run() {
var delay = 3000; //-- 3 seconds
$( '#message' ).text('Please wait ' + delay + ' seconds...');
setTimeout(whenDelayIsOver, delay);
function whenDelayIsOver() {
$( '#message' ).text('Done');
}
}
Try this http://jsfiddle.net/aamir/23ZFY/11/
function Run() {
var secs = 3;
$('#message').text('Please wait '+ secs +' seconds...');
var timer = setInterval(function () {
if (secs == 1) {
clearTimeout(timer);
$('#message').text('Done');
return;
}
secs--;
$('#message').text('Please wait ' + secs + ' seconds...');
}, 1000);
}
The browser's display is only updated when the function completely finishes running.
You can run the second lot of code asynchronously by using setTimeout.
function Run() {
$('#message').text('Please wait 3 seconds...');
setTimeout(
function () {
var start = new Date().getTime();
while (true) {
current = new Date().getTime();
if ((start + 3000) < current) {
break;
}
}
$('#message').text('Done');
},0);
}
You have a very tight loop (while(true)...) which doesn't allow the UI to update at all. What you can do instead is this:
function Run() {
var delay = 3000; //-- 3 seconds
$('#message').text('Please wait ' + (delay/1000) + ' seconds...');
setTimeout(function () {
$('#message').text('Done');
}, delay);
}
Basically, set the "wait message" initially and use the setTimeout function to update the message again after 3 seconds.
Updated fiddle.
I have a code in my js file.
function makeScrollable(wrapper, scrollable){
...
// Hide images until they are not loaded
scrollable.hide();
var loading = $('<div class="loading">Loading...</div>').appendTo(wrapper);
// Set function that will check if all images are loaded
var interval = setInterval(function(){
var images = scrollable.find('img');
var completed = 0;
if (completed == images.length) {
clearInterval(interval);
// Timeout added to fix problem with Chrome
setTimeout(function(){
loading.hide();
....
}, 1000); //end of setTimeout(func, delay)
} //end of if (completed == images.length)
}, 100); //end of var interval = setInterval(fn, 100)
...
}
(function(){
makeScrollable("div.sc_menu_wrapper", "div.sc_menu");
})(jQuery);
But my timeout function isn't calling. I am still getting the loading Div. Function should be call after 1 sec, which hide the loading div and execute code after. But it isn't happening. What i am doing wrong?
Thanks
Wrong position of code.
var completed = 0;
if (completed == images.length) { // This will be true only when there are no images
clearInterval(interval);
setTimeout(function(){
loading.hide();
....
}, 1000);
}
put it outside
var completed = 0;
var interval = setInterval(function(){
var images = scrollable.find('img');
if (completed == images.length) {
clearInterval(interval);
// Timeout added to fix problem with Chrome
setTimeout(function(){
loading.hide();
....
}, 1000); //end of setTimeout(func, delay)
} //end of if (completed == images.length)
}, 100); //end of var interval = setInterval(fn, 100)
And hope you are incrementing completed somewhere in the code