jQuery Set wait time before a function executes - javascript

How can i set wait time for this function.
function UpdateMedicaitonHistory(data) {
MedicaitonHistoryGrid();
//set a wait time to finish MedicaitonHistoryGrid() like for 3 seconds
// then execute the below code.
if ($("#MedHistoryGridSec").is(":visible")) {
alert("yes we have grid");
}
else{
alert("No Grid");
}
}

You can use setTimeout:
setTimeout(function()
{
if($('#MedHistoryGridSec').is(':visible'))
alert('yes');
else
alert('no');
}, 3000);

You could wrap up the code in a callback function and run it after three seconds using window.setTimeout:
var afterThreeSeconds = function() {
if ($("#MedHistoryGridSec").is(":visible")) {
alert("yes we have grid");
}
else{
alert("No Grid");
}
}
window.setTimeout(afterThreeSeconds, 3000);

Can you add a parameter to the medication history grid function taking a function containing the code you want executed after that function succeeds which you can then call at the end of the medication history grid function?

Related

SetInterval does not work when it is in another function?

When I put setInterval(autoAdmit, 1000) just below the autoAdmit() function, it works but when I place it in the if statements of another function, it does not work. Any ideas on why this is happening? I can't find anything that's wrong with it. forgot to mention: the part not working is the autoAdmit() function. When I put a console.log in the function, it still logs but what is inside the for loop is not executed for some reason.
let clickIntervalId = null;
function autoAdmit() {
for (let element of document.getElementsByTagName('span')) {
if (element.innerHTML === 'Admit') {
console.log('There is someone waiting to join this meeting, automatically admitting them...');
element.click();
}
}
}
//setInterval(autoAdmit, 1000) (if it is placed here it works)
document.addEventListener('DOMContentLoaded', function() {
var checkbox = document.querySelector('#auto-admit .mdc-switch__native-control');
function isChecked() {
if (checkbox.checked ) {
// do this
if(clickIntervalId) clearInterval(clickIntervalId);
clickIntervalId = setInterval(autoAdmit, 1000); //(if it is placed here, it doesn't work)
console.log('checked')
} else {
// do that
clearInterval(clickIntervalId);
console.log('not')
}
}
checkbox.addEventListener('change', function() {
isChecked();
});
function check() {
isChecked();
}
setTimeout(check, 2000)
}
);

Stop a recursive function

I am completely new in javascript and jquery... I have searched but can not find an answer to my problem...
I need to stop a function that call itself at the end (I read that this is called recursive function)
So my html
<div id="slide_show"></div>
Stop
My js
//call effect on load
$(function() {
moveSlide(true);
});
//move the div
function moveSlide(repeat) {
if(repeat === true) {
$('#slide_show').slideToggle('slow',function() {
setTimeout(function() {
moveSlide(true);
},2000);
});
} else {
return;
}
}
//stop the function
$(document).on('click','.stop',function(e) {
e.preventDefault();
moveSlide(false);
});
The function is called forever but I want to stop the function of being repeated when I click the button
What am I doing wrong?
Try with: clearTimeout() in else condition .
You need to create the setTimeout() in one variable.Then apply the clearTimout() if the condition is false(Its means a else statement)
var timer;
//call effect on load
$(function() {
moveSlide(true);
});
//move the div
function moveSlide(repeat) {
if(repeat === true) {
console.log('running')
$('#slide_show').slideToggle('slow',function() {
timer = setTimeout(function() {
moveSlide(true);
},2000);
});
} else {
clearTimeout(timer);
console.log('stopped')
return;
}
}
//stop the function
$(document).on('click','.stop',function(e) {
e.preventDefault();
moveSlide(false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="slide_show"></div>
Stop
I see that you are calling ever time at the method moveSlide, into the setTimeout
$('#slide_show').slideToggle('slow',function() {
setTimeout(function() {
**///moveSlide(true); ///here , will be calling recursive untill end**
},2000);
});
Test and tell us, if will help it
tks

Execute a Function after all slideDowns/slideUps are completed

I have this jQuery function which runs jQuery slideUp/slideDown.
There are two slide Options which would get executed at a time.
Here's the code:
updateView: function(){
var falseItems = jQuery(".cjs-milestone-task-container-false");
var trueItems = jQuery(".cjs-milestone-task-container-true");
var linkObject = jQuery("#cjs_milestones_see_all");
if(jQuery(MentoringModelMilestones.milestoneBlock).data("mode") == MentoringModelMilestones.viewStatus){
linkObject.html(linkObject.data("collapsed"));
linkObject.addClass("collapsed");
**falseItems.slideUp();**
MentoringModelMilestones.toggleSeeAll(falseItems.length == 0);
}
else{
linkObject.html(linkObject.data("expanded"));
linkObject.removeClass("collapsed");
**falseItems.slideDown();**
MentoringModelMilestones.toggleSeeAll(trueItems.length == 0);
}
**trueItems.slideDown();**
},
I need to call this function after the slideUp/slideDown are completed:
addMergeTop: function(){
jQuery(MentoringModelMilestones.milestoneBlock).find(".cjs_milestone_container").addClass('merge-top');
jQuery(MentoringModelMilestones.milestoneBlock).find(".cjs_milestone_container:visible").first().removeClass('merge-top');
},
Passing this as a function to slideUp/slideDown doesn't work.
It sounds like you want to chain the calls to slideUp and slideDown:
falseItems.slideUp(400 /* duration */, function() {
trueItems.slideDown(400, function() {
/* perform actions that should be done after both animations complete */
console.log("all animations done");
});
});
You'll need to do something similar for both cases of the if/else.
Note that this will perform one operation after the other. If you want both operations to occur simultaneously (or if you don't want to merge these two calls), then you'll need to do something hackier to maintain shared state. For example:
function slideAll() {
var count = 0;
$("#falseItems").slideUp("slow" /* duration */ , function() {
if (2 === ++count) {
alert("all done");
}
});
$("#trueItems").slideDown("slow", function() {
if (2 === ++count) {
alert("all done");
}
});
}
slideAll();
You don't have to do all of this in one slideAll function, but (however you do it) you do need to keep track of which animations have finished before you execute any code that relies on both.
See the second example in action:
http://jsfiddle.net/EKJGx/
Attach the callback function as a second parameter of your slideUp() or slideDown().
FIDDLE
function doSlide(){
$('.slider').slideUp(1000,function(){
alert('done sliding');
})
}
You can do like this. I am giving only a logic you can modify it to your needs
//place this at top
var falseItemsComplete = trueItems = false;
//modify below things in your code
falseItems.slideUp('fast', function() {
falseItemsComplete = true;//slideup for falseItems completed
checkCompletedStatus();
});
trueItems.slideDown('fast', function() {
trueItemsComplete = true;//slideup for trueItems completed
checkCompletedStatus();
});
function checkCompletedStatus(){
if(falseItemsComplete && trueItemsComplete ){
//both animations complete
alert(1)
}
}

How to call a function a fixed number of times after fixed intervals in javascript

I want to call an on event function a fixed number of times and after fixed interval of time.
Example of the code which is not working
function work(i){
remove();
draw(i);
}
d3.select("body").select('button').on('click', function() {
for(var i=0;i<7;i++){
setTimeout(function(i){
remove();
draw(i);
},1500);
}
});
What is the problem with my code and please provide the solution.
All your setTimeout calls are made immediately after each other in the loop and do not wait for each other to complete. You can use setInterval to achieve the functionality you requrie:
function work(i) {
remove();
draw(i);
}
d3.select("body").select('button').on('click', function () {
work(0);
var times = 1,
myInterval = setInterval(function () {
work(times);
times++;
if (times === 7) {
clearInterval(myInterval);
}
}, 1500);
});
Try this simple soln using setTimeout
function work(i){
remove();
draw(i);
if(i<=7){//set your condition
setTimeout(function(i){
i++;
work(i);
},1500);
}
}
d3.select("body").select('button').on('click', function() {
work(0);
});
I think, using setTimeout is safer than setInterval

Javascript : Do Action after elapsed time

I have a page where I fire an ajax request AND show a loading sign for the first 6 seconds after the user presses a button :
<button onclick="runLoader();"></button>
<script>
var startTime=(new Date).getTime();
function runLoader(){
runAjax();
var i=0;
var timer = setInterval(function(e){
i++;
//code for loading sign
if(i==3)
clearInterval(timer);
} ,2000);
}
function runAjax(){
$.ajax({
//
}).done(function(){
var timer2 = setInterval(function(){
var d = new Date();
var t = d.getTime();
if(t-startTime>=6000){
clearInterval(timer2);
// do X
}
},500);
}
}
</script>
I want to do action X only after both runLoader() has run for 6 seconds and runAjax() has resulted in a response, and no sooner.
Like, if runAjax() responds in 2 seconds, I still want to continue showing loading sign for 6 seconds and then perform X.
And if the loading sign has shown for 6 seconds, I want to wait for runAjax() to return for as long as it takes.
But using the Date() method is giving inaccurate results. For eg : It shows 7.765 s elapsed even when only 2 s have passed. I read somewhere I should use console.log(time) for better accuracy, but it doesnt work in <=IE9.
Is there a better way to approach this problem ?
Note: I am using setInterval() instead of setTimeout() because the loading involves cycling through an array of 3 elements, "Fetching", "Processing" and "Loading" each shown for 2 seconds :)
I would use deferreds and $.when:
function start(){
$.when(runLoader(), runAjax()).done(function() {
//both are now finished
});
}
function runLoader() {
//show loader here
var def = $.Deferred();
setTimeout(function() {
//hide loader here
def.resolve(true);
}, 6000);
return def.promise();
}
function runAjax() {
var def = $.Deferred();
$.ajax({...}).done(function(result) {
//handle response here
def.resolve(true);
});
return def.promise();
}
I would set a flag to mark it as "ready". There may be better ways to handle this, but this is just off the top of my head.
<script>
function runLoader(){
runAjax();
var i=0;
var timer = setInterval(function(e){
i++;
//code for loading sign
if(i==3)
clearInterval(timer);
} ,2000);
}
function runAjax(){
var timeElapsed = false;
setTimeout(function(){timeElapsed = true}, 6000);
$.ajax({
//
}).done(function(){
var timer2 = setInterval(function(){
if(timeElapsed){
clearInterval(timer2);
// do X
}
},500);
}
}
</script>
You can create a pre-caller function that is run on runLoader() and as callback of runAjax(), that will verify if the other action is complete, and then do action X. Example:
var ajaxDone = false;
var loaderDone = false;
function doActionX() {
//your action happens here
}
function tryToDoX() {
if (ajaxDone && loaderDone) {
doActionX();
}
}
function runLoader(){
loaderDone = false;
runAjax();
//show loading sign
setInterval(function(e){
//hide loading sign
clearInterval(timer);
loaderDone = true;
tryToDoX();
}, 6000);
}
function runAjax(){
ajaxDone = false;
$.ajax({
//whatever
}).done(function(){
ajaxDone = true;
tryToDoX();
}
}
It isn't necessary to make a recurring timeout and poll both statuses, because they only get completed once (in every run, i.e. booleans aren't set to false and true while waiting).
EDIT: This approach can be used to any asynchronous code that doesn't change status intermitently, even without jQuery.

Categories