Continue function after page reload? - javascript

function test() {
console.log("Hi");
setTimeout(function() {
location.reload();
console.log("Hi2");
}, 1000);
}
test();
Hi everyone i wonder if there is any chance that i can continue function/save progress of a function? What do i exactly mean with that? Well look at the code above. As you can see i have simple console.log, after it i setup a timeout for 1 sec, and i am reloading a page. I'ts clear that the console.log after page reload won't work, and here is my question. Is it possible to run that console.log after page reload, without triggering this first console.log?

Here is one way, I would have done it: using localStorage
localStorage.messages = []; //define an array to store all your messages
localStroage.messages.push('Hi');
localStroage.messages.push('Hi 2');
// don't call that line more than once, otherwise it will wipe out existing data
function test() {
check_messages();
setTimeout(function() {
location.reload();
check_messages();
}, 1000);
}
function check_messages() {
if (localStorage.messages.length>0) {
alert(localStorage.messages[0]); //display the message
localStorage.messages.splice(0,1); //get rid of it
}
}
test();

Related

how to run a function only once in javascript on every reload/refresh

Is there any way to load a function only once on first ever reload/refresh and other function to execute on every reload/refresh.
this is how it should look
var my_Var = set_Interval(my_Timer, 7000);
function my_Timer()
{
location.reload();
}
function to_Execute_Once()
{
}
function to_Execute_Every_Time()
{
}
Well, you could use localStorage:
var isFirstLoad = localStorage.getItem('isFirstLoad');
if (!isFirstLoad) {
to_Execute_Once()
localStorage.setItem('isFirstLoad', 'true');
}
I'll suggest to use localStorage(). On very first load of page set method execution variable in localStorage() and on successive reloads you can handle your function call based on that execution variable present in localStorage.

Code doesn't run in order? Updates to DOM happen all at once?

I'm having a bit of trouble with running my code in order. Basically I have a function that hides an element, console log a message then run another function that makes a slow and massive change to the DOM.
Ideally the hide occurs first to signal the user response has been made, then they can deal with the lag for a few seconds as everything refreshes. But right now, the console gets logged first, then all the changes happen at once after a few seconds. So the hide occurs together with the updates.
If it makes any difference, the update function creates and destroys several div elements, then starts creating JSXGraphs and updating functions, points, etc on those graphs.
check_answer(answer_input) {
if (this.ans == answer_input) {
$("#answer-card-section").hide();
console.log("CORRECT!");
current_question.update();
return true;
}
else {
return false;
}
}
Thanks!
When executing long running functions in JS the calls to render the UI can be blocked. In some cases it can also prevent the previous operation from visibly updating the DOM, which is what you're seeing here.
The simple fix is to put the update() call within a timeout with a short delay. This will allow the hide() to update the DOM first. Try this:
function check_answer(answer_input) {
if (this.ans == answer_input) {
$("#answer-card-section").hide();
setTimeout(function() {
current_question.update();
}, 25);
return true;
}
else {
return false;
}
}
It seems that you need to execute a callback function after all the hide-operations are finished. One way to achieve this in jQuery is to use $.when().done:
function check_answer(answer_input) {
if (this.ans == answer_input) {
$.when( $("#answer-card-section").hide() ).done(function() {
current_question.update();
});
return true;
} else {
return false;
}
}
But beware, in general the return of this function will happen before current_question.update() has been finished.

How can I automatically change a page in Javascript?

Trying to get the code to automatically change page using setTimeout, but I do not get it to work.
setTimeout()(page3, 500);
function page3() {
changepage3('automatic')
}
This is what my code looks like right now, but I am suspecting that this is not enough. Anyone knows what is missing?
try this one
function page3() {
changepage3('automatic')
}
setTimeout(page3, 500);
setTimout needs a specific syntax to work, check it out on the best JavaScript documentation by Mozilla: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Syntax
Here is an example
saySomethingAfter(5);
function saySomethingAfter(second) {
setTimeout(saySomething, second * 1000);
}
function saySomething() {
console.log("Something");
}
Your question is "How can I automatically change a page in Javascript?" using setTimeout. Let's analyse the needs:
change a page → open a new URL (cf. Open URL in same window and in same tab)
automatically using setTimeout → with the correct syntax
function changePage(url) {
window.open(url, "_self");
}
function changePageAfter5sec(url) {
setTimeout(function() {
changePage(url)
}, 5000);
}
changePageAfter5sec("https://stackoverflow.com")
Another way using beautiful functional JavaScript:
function changePage(url) {
return () => {
window.open(url, "_self");
}
}
function changePageAfter(second) {
return (url) => {
setTimeout(changePage(url), second*1000);
}
}
const changePageAfter5sec = changePageAfter(5);
changePageAfter5sec("https://stackoverflow.com")
You have 2 major problems in the code snippet provided:
That is not correct setTimeout() syntax - thus it doesn't actually work.
Even if it did work, it would call 1 function that uses another function which doesn't exist thus breaking the code.
fix problem number 1:
window.setTimeout(changePage, 5000);
now we have a running timeout that will trigger 5000 milliseconds after initiation(usually).
so let's fix problem 2 and let changepage() call an actual proper url opening function:
function changePage(){
window.open(urlOfPage3);
}
Finally a simpler version with an anonymous callback function in the setTimeout:
window.setTimeout(function(){
window.open(urlOfPage3);
}, 5000);

Stop a setTimeout function in AngularJS (hint: use $timeout)

I'm making a quiz-type app in which, when user gets a question, a timer of 10 seconds goes like this:
$scope.timer2 = function() {
setTimeout(function() {
console.log('times up!!!!');
}, 10000)
}
and it is being called when a question arrives like this:
timerHandle = setTimeout($scope.timer2());
And after this timer2 execution another question pops up and so on, another way of a question being popped up is that the user selects an option also then a new question comes up. So far so good but the problem is that if suppose 5 seconds were passed and then user selects an option, the "timer2" still shows "times up!!" after 5 more seconds and another timer for the new question also shows "times up!!" if the user hasn't selected any option.
What I'm trying to say is that I want the timer2 to stop when user selects any option, and then i want again this timer to be called as a new question will arrive.
This is the angular code which executes when user selects an option:-
$scope.checkanswer=function(optionchoosed){
$http.get('/quiz/checkanswer?optionchoosed='+ optionchoosed).then(function(res){
if(res.data=="correct"){
$scope.flag1=true;
$scope.flag2=false;
}else{
$scope.flag2=true;
$scope.flag1=false;
}
$http.get('/quiz/getquestions').then(function(res){
console.log("respo");
$scope.questions=res.data;
clearTimeout($scope.timerHandle); //not working
timerHandle = setTimeout($scope.timer2());
You can try using the service of AngularJS $timeout.
Then do something along these lines:
var myTimer = $timeout(function(){
console.log("hello world")
}, 5000);
....
$timeout.cancel(myTimer);
Take a look at the MDN documentation for setTimeout.
As you can see, that function returns a unique identifier.
At this point, you can call clearTimeout passing that UID as parameter:
let myTimeout = setTimeout(myFunction, millis); //Start a timeout for function myFunction with millis delay.
clearTimeout(myTimeout); //Cancel the timeout before the function myFunction is called.
Since you do not provide working example let me do the best guess. Your function does not return handle from inner setTimeout so it cannot be cancelled. What about such modifications:
$scope.timer2 = function() {
return setTimeout(function() { // added return statement
console.log('times up!!!!');
}, 10000)
}
and then
timerHandle = $scope.timer2(); // simply call timer2 that returns handle to inner setTimeout

How to use Ajax to populate externally loaded div (jQuery)

I am creating tests for a page and HAVE to use jQuery to change elements on the control version of the page for each different experience.
I'm using jquery to load an element from an external page and replace a div. However, on the external page, it uses an ajax call to an api to populate the div, so I copied over the function with the ajax call.
I think it is attempting to make the ajax call before the new div is actually loaded on the page.
I've tried moving the function, wrapping the load function within the ajax call, but it still doesnt work.
I could be missing something obvious, but here's that part of my code:
$('.replace-div').load('external.html #replace-div');
function waitForLoad() {
if ($('#replace-div')) {
var object;
$.ajax({
url: "https://api.com",
async: false,
success: function(result) {
object = result;
var variable1 = object["blah"][0].value,
var variable2 = object["blah"][0].value,
var variable3 = object["blah"][0].value,
var variable4 = object["blah"][0].value,
$('newElement').attr('href', variable1);
$('newElement2').attr('src', variable2);
$('newElement3').attr('href', variable3);
$('newElement4').text("text" + variable4 + "more text");
}
});
} else {
setTimeout(waitForLoad, 15);
}
}
waitForLoad();
I don't get any errors in the console, and when I paste the above waitForLoad function into the console, it populates totally fine. obviously this is after the page loads the new div, so i just need to know how to make the ajax call wait for the load.
I've tried .ajaxComplete(), but it doesnt help.
$(function() {}); also does not work
.load() has a callback argument where you supply a function to run after the data is loaded.
$('replace-div').load('external.html #replace-div', function() {
$.ajax(...);
});
So, what happens is that, once waitForLoad is called for the first time, it doesn't see the div loaded, the code goes to the else block and executes again with a 15ms timeout. 15ms is not enough for the div to load, most likely.
You can try three things (ordered from worse to better):
Try increasing the timeout to a bigger number. Start with 1000 (1000ms - 1 second) and see if it works or you need to increase it. It's more likely you'll have to decrease it
Try using setInterval instead of setTimeout, which will repeat itself. Of course, once it loads, you'll need to clear the interval so it stops. Also, better use bigger timeouts/intervals, like 50 or 100ms b/c the fast firing timers can slow down a page a lot
E.g.
$('.replace-div').load('external.html #replace-div');
function waitForLoad() {
if ($('#replace-div')) {
clearInterval(window.waiter);
...
} else {
window.timer = setInterval(waitForLoad, 50);
}
}
waitForLoad();
Same as 2, but using more idiomatic callback function after load call.
// the window.waiter is the interval handle, and it will run every 100ms. It calls .load every time, and if the #replace-div is found, unsets the interval handle.
window.waiter = setInterval(function() {
$(".replace-div").load("external.html #replace-div", function() {
if ($(".replace-div #replace-div").length) {
// found the DIV
// code...
clearInterval(window.waiter); // bye interval handle, thanks
}
});
}, 100);

Categories

Resources