Delay/Wait in between appending DIV in Ajax - javascript

I have below code where I am trying to display a message (in the form of DIV) by delaying certain amount of time in between appending div tags, I have only very little knowledge on Ajax, and tried to find a solution but I am not able to get it to work.
The below code when I try to execute it's not waiting for 2 seconds, and continuously appends div messages without any delay.
Can someone guide me please?
Here is my code
<script>
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function wait_for_some_time() {
await sleep(2000);
}
$(function () {
$("#btn-chat").click(function (event) {
event.preventDefault();
if ($("#mes_resp").val() != "") {
$("#form-chat").submit();
}
});
$("#form-chat").submit(function (event) {
event.preventDefault();
var user_input = $("#mes_resp").val();
var pre_key = $("#pre_key").val();
if (user_input != "") {
$(".media-list").append('<div class="bubble-line"><div class="bubble bubble--alt">' + user_input + '</div></div> <div></div>');
if ((user_input == "yes" && pre_key == "duration")) {
i = 0;
while (i < 10) {
$(".media-list").append('<br>');
$(".media-list").append('<div class="thought"><div class="bubble">' + "Your request is in progress" + '</div></div> <div></div>');
$(".panel-body").stop().animate({ scrollTop: $(".panel-body")[0].scrollHeight }, 1000);
$("#mes_resp").val('');
wait_for_some_time();
i++;
}
}
}
$("#mes_resp").val('')
});
});</script>

Try putting the await keyword next to your call to the wait_for_some_time() function.

I replaced with setInterval() and it worked great, In case if anyone is looking for
<script>
function continueExecution() {
$(".media-list").append('<br>');
$(".media-list").append('<div class="thought"><div class="bubble">' + "Your request is in progress" + '</div></div> <div></div>');
$(".panel-body").stop().animate({ scrollTop: $(".panel-body")[0].scrollHeight }, 1000);
$("#mes_resp").val('');
}
$(function () {
$("#btn-chat").click(function (event) {
event.preventDefault();
if ($("#mes_resp").val() != "") {
$("#form-chat").submit();
}
});
$("#form-chat").submit(function (event) {
event.preventDefault();
var user_input = $("#mes_resp").val();
var pre_key = $("#pre_key").val();
if (user_input != "") {
$(".media-list").append('<div class="bubble-line"><div class="bubble bubble--alt">' + user_input + '</div></div> <div></div>');
if ((user_input == "yes" && pre_key == "duration")) {
var timer;
timer = setInterval(function () {
i = 0;
while (i < 10) {
continueExecution();
i++;
}
clearInterval(timer);
}, 3000);
}
}
$("#mes_resp").val('')
});
});</script>

Related

Adding additional case to script for onClick event

I have a pop-up for a website that asks the user to sign up if they aren't already signed in. I'm using a script called "subscribe-better.js" (https://github.com/peachananr/subscribe-better) and this works great for loading the popup when the user first enters the site.
However, I want this pop-up to show when a user clicks a button. This is my button:
<div id="popClick" class="button btn">Sign Up to Proceed</div>
and here is how I am calling the pop-up:
<script>
$(document).ready(function() {
$(".subscribe-me2").subscribeBetter({
trigger: "onclick",
animation: "fade",
delay: 0,
showOnce: true,
autoClose: false,
scrollableModal: false
});
});
</script>
<div class="subscribe-me2">
Sample Pop Up Content Here
</div>
And the code to make it pop-up. You'll see I've added the case for onclick but nothing is happening when I click my button. I also tried instead of document.ready() to call the pop-up within a $('#popClick').click() but that didn't make the pop-up appear either. How can I fix the switch statement to make the pop-up appear when the #popClick button is clicked?
!function($){
var defaults = {
trigger: "atendpage", // atendpage | onload | onidle
animation: "fade", // fade | flyInRight | flyInLeft | flyInUp | flyInDown
delay: 0,
showOnce: true,
autoClose: false,
scrollableModal: false
};
$.fn.subscribeBetter = function(options){
var settings = $.extend({}, defaults, options),
el = $(this),
shown = false,
animating = false;
el.addClass("sb");
$.fn.openWindow = function() {
var el = $(this);
if(el.is(":hidden") && shown == false && animating == false) {
animating = true;
setTimeout(function() {
if (settings.scrollableModal == true) {
if($(".sb-overlay").length < 1) {
$("body").append("<div class='sb-overlay'><div class='sb-close-backdrop'></div><div class='sb sb-withoverlay'>" + $(".sb").html() + "</div></div>");
$(".sb-close-backdrop, .sb-close-btn").one("click", function() {
$(".sb.sb-withoverlay").closeWindow();
return false;
});
$(".sb.sb-withoverlay").removeClass("sb-animation-" + settings.animation.replace('In', 'Out')).addClass("sb-animation-" + settings.animation);
setTimeout(function(){
$(".sb.sb-withoverlay").show();
$("body").addClass("sb-open sb-open-with-overlay");
}, 300);
}
} else {
if ($(".sb-overlay").length < 1) {
$("body").append("<div class='sb-overlay'><div class='sb-close-backdrop'></div></div>");
$(".sb").removeClass("sb-animation-" + settings.animation.replace('In', 'Out')).addClass("sb-animation-" + settings.animation);
$(".sb-close-backdrop, .sb-close-btn").one("click", function() {
$(".sb").closeWindow();
return false;
});
setTimeout(function(){
$(".sb").show();
$("body").addClass("sb-open");
}, 300);
}
}
if (settings.showOnce == true) shown = true;
animating = false;
}, settings.delay);
}
}
$.fn.closeWindow = function() {
var el = $(this);
if(el.is(":visible") && animating == false) {
animating = true;
if (settings.scrollableModal == true) {
$(".sb.sb-withoverlay").removeClass("sb-animation-" + settings.animation).addClass("sb-animation-" + settings.animation.replace('In', 'Out'));
setTimeout(function(){
$(".sb.sb-withoverlay").hide();
$("body").removeClass("sb-open sb-open-with-overlay");
setTimeout(function() {
$(".sb-overlay").remove();
}, 300);
}, 300);
} else {
$(".sb").removeClass("sb-animation-" + settings.animation).addClass("sb-animation-" + settings.animation.replace('In', 'Out'));
setTimeout(function(){
$(".sb").hide();
$("body").removeClass("sb-open");
setTimeout(function() {
$(".sb-overlay").remove();
}, 300);
}, 300);
}
animating = false;
}
}
$.fn.scrollDetection = function (trigger, onDone) {
var t, l = (new Date()).getTime();
$(window).scroll(function(){
var now = (new Date()).getTime();
if(now - l > 400){
$(this).trigger('scrollStart');
l = now;
}
clearTimeout(t);
t = setTimeout(function(){
$(window).trigger('scrollEnd');
}, 300);
});
if (trigger == "scrollStart") {
$(window).bind('scrollStart', function(){
$(window).unbind('scrollEnd');
onDone();
});
}
if (trigger == "scrollEnd") {
$(window).bind('scrollEnd', function(){
$(window).unbind('scrollStart');
onDone();
});
}
}
switch(settings.trigger) {
case "atendpage":
$(window).scroll(function(){
var yPos = $(window).scrollTop();
if (yPos >= ($(document).height() - $(window).height()) ) {
el.openWindow();
} else {
if (yPos + 300 < ($(document).height() - $(window).height()) ) {
if(settings.autoClose == true) {
el.closeWindow();
}
}
}
});
break;
case "onload":
$(window).load(function(){
el.openWindow();
if(settings.autoClose == true) {
el.scrollDetection("scrollStart", function() {
el.closeWindow();
});
}
});
break;
case "onidle":
$(window).load(function(){
el.scrollDetection("scrollEnd", function() {
el.openWindow();
});
if(settings.autoClose == true) {
el.scrollDetection("scrollStart", function() {
el.closeWindow();
});
}
});
break;
case "onclick":
$('#popClick').click(function(){
el.openWindow();
});
break;
}
}
}(window.jQuery);
I believe the problem is that you're using 'showOnce' which globally limits the popup from showing more than once. So, your onclick probably is firing (I'd suggest adding a console.log in to be sure) but then if(el.is(":hidden") && shown == false && animating == false) { in the openWindow function is no longer true.

Javascript - Check if key was pressed twice within 5 secs

I want to check if Enter key was pressed twice within 5 secs and perform some action.
How can I check if the key was pressed once or twice within a given time and perform different actions.
Here is my code:
<h1 id="log">0</h1>
<br/>
<span id="enteredTime">0</span>
<script>
$(document).keypress(function(e) {
if(e.which == 13){
var element = $("#log");
var timeDifference = 0;
//Log the timestamp after pressing Enter
$("#enteredTime").text(new Date().getTime());
//Check if enter was pressed earlier
if ($("#enteredTime").text() !== "0") {
var now = new Date().getTime();
var previous = $("#enteredTime").text();
difference = now - previous;
}
//Check if enter was pressed only once within 5 secs or more
if(){
$("#log").text("Once");
$("#enteredTime").text("0");
//Check if enter was pressed twice in 5 secs
}else{
$("#log").text("Twice in less than 5 secs");
$("#enteredTime").text("0");
}
}
});
</script>
http://jsfiddle.net/Rjr4g/
Thanks!
something like
var start=0;
$(document).keyup(function(e) {
if(e.keyCode == 13) {
elapsed = new Date().getTime();
if(elapsed-start<=5000){
//do something;
}
else{
//do something else;
}
start=elapsed;
}
});
Try a timer based solution like
var flag = false,
timer;
$(document).keypress(function (e) {
var element = $("#log");
var timeDifference = 0;
if (e.which == 13) {
if (flag) {
console.log('second');
clearTimeout(timer);
flag = false;
} else {
console.log('first');
flag = true;
timer = setTimeout(function () {
flag = false;
console.log('timeout')
}, 5000);
}
//Log the timestamp after pressing Enter
$("#enteredTime").text(new Date().getTime());
if ($("#enteredTime").text() !== "0") {
var now = new Date().getTime();
var previous = $("#enteredTime").text();
difference = now - previous;
}
}
});
Demo: Fiddle
Bacon.js seems like a good tool to express this.
$(document).asEventStream('keypress')
.filter(function (x) {
return x.keyCode == 13;
})
.map(function () {
return new Date().getTime();
})
.slidingWindow(2, 1)
.map(function (x) {
return (x.length == 1 || x[1] - x[0] > 5000) ? 1 : 2;
})
.onValue(function (x) {
$("#log").text(x == 1 ? "Once" : "Twice in less than 5 secs");
});
(fiddle)
here is my solutions, please check it if match your idea :)
(function($){
var element = $("#log");
var timeDifference = 0;
var count = 0;
$(document).keypress(function(e) {
if(e.which === 13){
//do what you want when enterpress 1st time
/*blah blah */
//after done 1st click
count++;
if(count === 2) {
//do what you want when enterpress 2nd time in 5 seconds
/* blah blah */
//after done
clearTimeout(watcher);
count = 0;
return;
}
//setTimeout to reset count if more than 5 seconds.
var watcher = setTimeout( function() {
count = 0;
},5000);
}
});
}(jQuery)
Check your Updated Fiddle
var count = 0;
$(document).keypress(function(e) {
var element = $("#log");
var timeDifference = 0;
if(e.which == 13){
count++;
console.log('enter pressed'+count);
if(count == 1){
startTimer();
}
else{
checkCount();
}
//Log the timestamp after pressing Enter
$("#enteredTime").text(new Date().getTime());
if ($("#enteredTime").text() !== "0") {
var now = new Date().getTime();
var previous = $("#enteredTime").text();
difference = now - previous;
}
}
});
function startTimer(){
setTimeout(checkCount,5000);
}
function checkCount(){
if(count == 1){
$("#log").text("Once");
$("#enteredTime").text("0");
//Check if enter was pressed twice in 5 secs
}else{
$("#log").text("Twice in less than 5 secs");
$("#enteredTime").text("0");
}
}
startTimer() starts counting on first enter press. And checkCount() contains your condition after 5secs.
setTimeout() lets you attach an event which occurs after a specific timespan.

clearInterval is not clearing

Take a look at the function below, It purpose is to change the button text
to "Abort", "Abort 0", "Abort 1" and so on.
Once the counter reaches 10 another function should be executed, but if
the button is clicked, the counter should stop, and the button text should return
to it's original value ("Sync DB").
It seems I'm trying to clear out the interval in a wrong way.
Any assistance will be appreciated.
function sync_database(abort)
{
if (abort == true) { sync_db_btn.innerHTML = "Sync DB"; return false }
sync_db_btn.innerHTML = "Abort"
var i = 0;
sync_db_btn.addEventListener("click", function() { sync_database(true) } );
var x = setInterval(function() {
if (abort == true) {
clearInterval(x);
}
if (i < 10) {
sync_db_btn.innerHTML = "Abort " + i++;
}
}, 1000);
}
var x;
sync_db_btn.addEventListener("click", function() {
sync_database(true);
clearInterval(x);
} );
function sync_database(abort)
{
if (abort == true) { sync_db_btn.innerHTML = "Sync DB"; return false }
sync_db_btn.innerHTML = "Abort"
var i = 0;
x = setInterval(function() {
if (i < 10) {
sync_db_btn.innerHTML = "Abort " + i++;
}
}, 1000);
}
I think you need something like this:
var sync_db_btn = document.getElementById('but'),
abortSync = -1,
interval,
sync_database = function () {
var i = 0;
abortSync *= -1;
if (abortSync < 0) {
sync_db_btn.innerHTML = 'Sync DB';
clearInterval(interval);
return false;
}
sync_db_btn.innerHTML = 'Abort';
interval = setInterval(function () {
if (i < 10) {
sync_db_btn.innerHTML = 'Abort ' + i++;
} else {
sync_db_btn.innerHTML = 'Sync DB';
clearInterval(interval);
abortSync = -1;
}
}, 1000);
};
sync_db_btn.addEventListener('click', sync_database);
A live demo at jsFiddle.

Better way to find all iframes on the page

I am developing iPad application in that more than 6 iframes are available. After fully loaded the page, the page scroll went to the some where in the middle. So I decided to get page scrolltop written JavaScript code like this:
$(document).ready(function() {
try {
var iframecompleted = [];
$("iframe[id*='iframe']").each(function(eli, el) {
$(this).bind("load", iframeinit);
});
function iframeinit() {
iframecompleted.push($(this).id);
$(this).unbind("load", iframeinit);
}
var timer = setInterval(function() {
if ($("iframe[id*='iframe']").length == iframecompleted.length) {
clearInterval(timer);
$('html, body').animate({
scrollTop: 0
}, 500);
if (FrameID != "") {
var j = 0;
var ss = FrameID.split(",")
for (j = 0; j < ss.length; j++) {
var collPanel = $find("pane" + ss[j]);
if (collPanel != null)
collPanel.set_Collapsed(true);
}
FrameID = "";
}
}
}, 10);
}
catch (e) {
alert(e);
}
});
}
I would like to find a better way to achieve this task. Your ideas are more welcome.
You could do something like this :
var count = 0;
$("iframe").load(function() {
if (++count === 6)
{
alert("TODO: All the frames are loaded, do you stuff");
}
});
http://jsfiddle.net/eDVEY/
You can do something like this:
var count = $('iframe').length;
$(function() {
$('iframe').load(function() {
count--;
if (count == 0)
alert('all frames loaded');
});
});
Hope it helps

JavaScript to delay execution of functions after page is loaded

I wrote this javascript to make an animation. It is working fine in the home page. I wrote a alert message in the last.
If I go other then home page, this alert message has to come, but I am getting alert message, if I remove the function, alert message working on all pages, any thing wrong in my code?
window.onload = function(){
var yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
var signUp = document.getElementById('signup-link');
if (yellows != 'undefined' && signUp != undefined){
function animeYellowBar(num){
setTimeout(function(){
yellows[num].style.left = "0";
if(num == yellows.length-1){
setTimeout(function(){
signUp.style.webkitTransform = "scale(1)";
},num*250);
}
}, num * 500);
}
for (var i = 0; i < yellows.length; i++){
animeYellowBar(i);
}
}
alert('hi');
}
DEMO: http://jsbin.com/enaqu5/2
var yellows,signUp;
window.onload = function() {
yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
signUp = document.getElementById('signup-link');
if (yellows !== undefined && signUp !== undefined) {
for (var i = 0; i < yellows.length; i++) {
animeYellowBar(i);
}
}
alert('hi')
}
function animeYellowBar(num) {
setTimeout(function() {
yellows[num].style.left = "0";
if (num == yellows.length - 1) {
setTimeout(function() {
signUp.style.webkitTransform = "scale(1)";
},
num * 250);
}
},
num * 500);
}
DEMO 2: http://jsbin.com/utixi4 (just for sake)
$(function() {
$("#magazine-brief h2").each(function(i,item) {
$(this).delay(i+'00').animate({'marginLeft': 0 }, 500 ,function(){
if ( i === ( $('#magazine-brief h2').length - 1 ) )
$('#signup-link')[0].style.webkitTransform = "rotate(-2deg)";
});
});
});
For starters you are not clearing your SetTimeout and what are you truly after here? You have 2 anonymous methods that one triggers after half a second and the other triggers a quarter of a second later.
So this is just 2 delayed function calls with horribly broken syntax.
Edited Two possibilities, one fixes your current code... the latter shows you how to do it using JQuery which I would recomend:
var yellows, signUp;
window.onload = function(){
yellows = document.getElementById('magazine-brief');
if(yellows != null){
yellows = yellows.getElementsByTagName('h2');
}else{
yellows = null;
}
signUp = document.getElementById('signup-link');
if (yellows != null && signUp != null && yellows.length > 0)
{
for(var i = 0; i < yellows.length; i++)
{
animeYellowBar(i);
}
}
alert('hi');
}
function animeYellowBar(num)
{
setTimeout(function(){
yellows[num].style.left = "0";
if(num == yellows.length-1){
setTimeout(function(){
signUp.style.webkitTransform = "scale(1)";
},num*250);
}
}, num * 500);
}
The below approach is a SUMMARY of how to use JQuery, if you want to use JQuery I'll actually test it out:
//Or using JQuery
//Onload equivelent
$(function(){
var iterCount = 0,
maxIter = $("#magazine-brief").filter("h2").length;
$("#magazine-brief").filter("h2").each(function(){
setTimeout(function(){
$(this).css({left: 0});
if(iterCount == (maxIter-1))
{
setTimeout(function(){
signUp.style.webkitTransform = "scale(1)";
},iterCount*250);
}
}, iterCount++ * num );
});
});

Categories