run function only once on first pageload - javascript

i have 3 divs , i want that on first time the page is loaded the function init runs,not again after tht on refresh or reload of page. but its not working below is my code, it runs the code even on refresh or reload of the page.
function _(x){
return document.getElementById(x);
}
$(document).ready(function(){
init();
});
function init() {
_("page1_id").style.display = "none";
_("page2_id").style.display = "none";
_("page0_id").style.display = "block";
}
i am a newbie so kindly share the code tht i need to add or change..thank u

Set a cookie init_run = true
then check it before running init()
or inside the init function:
function init (){
if ( cookie is set )
return;
...
}

Related

execute js function after reloading page [duplicate]

I'm trying to refresh a page and then run a function once the refresh has been completed. However the code I have now, runs the function and then it only refreshes it, meaning I lose what the function did. Is there a way to solve this?
My code
function reloadP(){
document.location.reload();
myFunction();
}
<button onclick: "reloadP()">Click</button>
You need to call myFunction() when the page is loaded.
window.onload = myFunction;
If you only want to run it when the page is reloaded, not when it's loaded for the first time, you could use sessionStorage to pass this information.
window.onload = function() {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
myFunction();
}
}
function reloadP() {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}
DEMO
function myFunction() {
document.getElementById("welcome").textContent = "Welcome back!";
}
window.onload = function() {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
myFunction();
}
}
function reloadP() {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}
DEMO: https://jsfiddle.net/barmar/5sL3hd74/
Adding to #Barmar answer... In case you'd like to use session storage only when a button in the page is clicked and not when reloading with the browser button, you can use sessionStorage.clear() or sessionStorage.removeItem() once you've executed the function after loading the window.
So, let's say we have:
let restart = sessionStorage.getItem("restart")
Set restart boolean to true as a session storage and reload:
resetBtn.addEventListener("click", () => {
sessionStorage.setItem("restart", "true")
location.reload()
})
Once the window is reloaded we can execute the following function:
window.onload = () => {
if(restart){
// Do something
sessionStorage.clear() // This cleans all the session storage
// If you want to remove ONLY the item from the storage use:
// sessionStorage.removeItem("restart")
}
};
So, if now the user reloads the page with the browser button it will reload with the session storage cleaned. Meaning, no functions will be executed after window load.
In my case i used Barmar's solution. I have a modal popup form, i want to submit the form then automatically refresh the page and finally success message on reloaded page.
var form = document.getElementById('EditUserInfosForm')
form.addEventListener('submit', function () {
sessionStorage.setItem("reloading", "true");
document.location.reload();
})
window.onload = function () {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
$('#success-message-modal').modal('show')
}
}
Probably simplest approach.
HTML Button
Reload button (credits):
<!-- index.html -->
<button onClick="window.location.reload();">Refresh Page</button>
JS Code
Run your code after reload:
// index.js
window.addEventListener("load", (event) => {
YourFunction(); // already declared somewhere else
});
You may not use event variable at all.
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event#examples

Calling Dynamically Loading JS method Using Callbacks is Not Working

This code leads to :Uncaught error : check is not defined.Can some one help regarding this code snippet. Please find below code
The check() is define in external .js file
Method in script tag ...
<script>
loadScriptfinal("/js/VendorPaymentInfo/"+coreId+".js", function() {
check();
});
function loadJS(file,callback) {
var jsElm = document.createElement("script");
jsElm.type = "application/javascript";
jsElm.src = file;
jsElm.onload = function() {
callback();
}
// finally insert the element to the body element in order to load the script
document.body.appendChild(jsElm);
}
</script>
You can watch till the external file is loaded and then call loadScriptfinal function.
var timer = null;
var timer = setInterval(()=>{
if (window.check && window.check.constructor === Function) {
clearInterval(timer);
loadScriptfinal("/js/VendorPaymentInfo/"+coreId+".js", function() {
check();
});
}
},100)

Redirect with inactivity

My objective is to keep a user in a view as long as he/she keeps clicking a button within a certain lapse.
I'm using Rails and was exploring a solution via an embedded JS in the pertinent view.
So far I'm able to set a time after which the user will be redirected to root path with the following script:
var delayedRedirect = function (){
window.location = "/";
}
var delay = 10000;
$(document).ready(function() {
setTimeout('delayedRedirect()', delay);
});
I've been trying to write a function that resets the value of 'delay'or that calls the setTimeoutFunction again.
$('#btn-persist').click(function() {
delay = 3000;
// or calling again setTimeout('delayedRedirect()', delay);
});
But I noticed that changing the variable won't affect the setTimeout function that has already been called.
I've also tried to use the clearTimeout function as below without success
var delayedRedirect = function (){
window.location = "/persists";
}
var delay = 3000;
var triggerRedirect = function() { setTimeout('delayedRedirect()', delay);
}
var stopRedirect = function (){
clearTimeout(triggerRedirect);
}
$(document).ready(function() {
triggerRedirect();
$('#btn-persist').click(function() {
stopRedirect();
});
});
I wonder why this may not be working and if there's any other way to stop the execution of the setTimeout function that has already been called so I can call it again to effectively reset the time to the original value of 'delay'.
At the same time, I don't want to stop any other JS functions that are running in parallel.
Do you see a better solution to achieve this?
The main problem why clearTimeout is not working. because you are clearing a anonymous function instead of a setTimeout variable
change this
var triggerRedirect = function() { setTimeout('delayedRedirect()', delay);
}
to this
var triggerRedirect = setTimeout('delayedRedirect()', delay);
Edit:
also change this (if you want to restart the inactive redirect trigger)
$('#btn-persist').click(function() {
stopRedirect();
});
to this
$('#btn-persist').click(function() {
stopRedirect();
triggerRedirect();
});

Javascript setTimeout fires as many times in as page loaded by ajax

I am executing setTimeout function in a page which loads via ajax call. but if i click the link to load the page again, i afraid the last setTimeout call still continues and the number of intervals of the calls set by setTimeout executes multiple times.
tried this is the remote page:
var RefreshInterval = null;
clearTimeout(RefreshInterval);
function someFunction()
{
....
setNextRefresh();
}
function setNextRefresh() {
console.log(wifiRadarRefreshInterval);
RefreshInterval = null;
clearTimeout(RefreshInterval);
RefreshInterval = setTimeout('someFunction();', 20*1000);
}
declare var RefreshInterval = null; outside of page loaded by ajax and use this code on the page:
clearTimeout(RefreshInterval);
function someFunction()
{
....
setNextRefresh();
}
function setNextRefresh() {
console.log(wifiRadarRefreshInterval);
clearTimeout(RefreshInterval);
RefreshInterval = setTimeout('someFunction();', 20*1000);
}
if i don't want to declare it in parent page, here is the solution i found:
//Clear previously loaded calls if exists
try{ clearTimeout(wifiRadarRefreshInterval); }catch(e){}
var wifiRadarRefreshInterval = null;
function somefunction(){
....
setNextRefresh();
}
function setNextRefresh() {
try{
clearTimeout(wifiRadarRefreshInterval);
wifiRadarRefreshInterval = null;
wifiRadarRefreshInterval = setTimeout('somefunction();', 20*1000);
}
catch(e){
console.log(e.message + e.stack);
}
}
Do not use this
var RefreshInterval = null;
clearTimeout(RefreshInterval);
You are actually assigning a null and then trying to clear it. Which will not work, The timeout must be cleared by using the clearTimeout and by passing the variable which was assigned to the setTimeout. Here you will end up passing a null so the timer is never cleared.
Here is a small sample which will demonstrate a fix to your problem JS Fiddle
So insted of setting the variable to null and then trying to clear it, Just check if the variable is not defined and if it is defined clear it, else move on. Use the code below, Also you must remove the top two lines as mentioned
function setNextRefresh() {
console.log(wifiRadarRefreshInterval);
if (typeof RefreshInterval !== 'undefined') {
clearTimeout(RefreshInterval);
}
RefreshInterval = setTimeout('someFunction();', 20*1000);
}
Click on the button say like 4 times, The output should be printed only once. That is if the ajax call is made 4 times the set time out must execute only once. Check below snippet for demo
var clickCount= 0; // just to maintain the ajax calls count
function NewPageSimilator(clicksTillNow) { // this acts as a new page. Let load this entire thing on ajaX call
if (typeof RefreshInterval !== 'undefined') {
clearTimeout(RefreshInterval);
}
function setNextRefresh() {
window.RefreshInterval = setTimeout(printTime, 3000); //20*1000
}
function printTime() {// dumy function to print time
document.getElementById("output").innerHTML += "I was created at click number " + clicksTillNow + '<br/>';
}
setNextRefresh();
}
document.getElementById("ajaxCall").addEventListener("click", function() { // this will act as a ajax call by loading the scripts again
clickCount++;
NewPageSimilator(clickCount);
});
document.getElementById("clear").addEventListener("click", function() { //reset demo
clickCount = 0;
document.getElementById("output").innerHTML = "";
});
<p id="output">
</p>
<button id="ajaxCall">
AJAX CALL
</button>
<button id="clear">
Clear
</button>

How to stop Ajax image load calling a new function?

I'm doing something like this ->
$("<img>").attr("src", "path/to/image.jpg").load(function(){
$("#thediv").append(this);
});
so i can append the new image when the image is completely loaded
I have a timer to call this function with new parameters every 6 seconds.... but I want to call a function to load a new set of images but I have this old set running in background ( asynchronous ) and i need to stop that load so the image won't append beacuse i don't want that image and I'm trying to load a whole new different set of images... I was thinking on something like :
function loadNewSet(){
window.stop(); // i don't quite know if this exist or works but
//should stop all ajax request taking place at that time
loadImages(); // call some function to load the new set
}
/*//*///*///*///*///*///*/
To be more specific:
I have a div called thediv where I'll be placing my images
then I have set of images or an array
set1 = ['img1','img2','img3']
and
set2 = ['img4','img5','img6']
and i have thetimer set on the
$(document).ready(function(){
thetimer=setTimeout("nextSlide()",6000);
});
then i have nextSlide()
function nextSlide(){
//this is where i load the next image on the active set (set 1 or set 2)
img.load(function(){
thetimer=setTimeout("nextSlide()",6000); // and then i set the timer again
});
}
but when the nextSlide() function is called it'd be like idle while the new image is loading and after it loads it'd the things it's supposed to do on load() but what it while loading i call this function loadNewSet()
function loadNewSet(set){
clearTimeout(thetimer);
//this is wheere i want to stop any image loading called by any other function
stopAllImagesLoading();//example
//then change activeset
activeSet=set; // set1 or set2
nextSlide();
}
Don't quite know if I'm doing this the right way and may be I can't put down the procces here the way I'm doing it.
Thanks for your responses.
You can spawn up "worker processes" by using setTimeout.
var proc;
somefunc();
function somefunc() {
//do stuff
proc = setTimeout(somefunc, 6000);
}
//...
clearTimeout(proc); //Cancel the looping somefunc from executing.
What if instead of appending, you do something like....
<div id="myDiv">
<img id="myImg" style="display: none">
</div>
...
function loadImg(url){
$("#myImg").attr("src", url).load(function(){
if(url == $(this).attr(url)){
// The currently requested image has loaded. Show it.
$(this).show();
}
else{
// Finished loading an image that we don't need anymore. Do nothing.
}
});
}
So if you called:
loadImg("a.jpg");
loadImg("b.jpg");
a.jpg might or might not finish first, but it doesn't matter because once a.jpg finishes, nothing happens.
Try using a global variable to turn on or off the timer. For instance (pseudo-code only):
var gKeepRunning = true; //KEY TO ANSWER HERE
myRepeatingImageLoader(); //this is the method that will repeat
function myRepeatingImageLoader(){
$("<img>").attr("src", "path/to/image.jpg").load(function(){
$("#thediv").append(this);
});
if( gKeepRunning == true ) //KEY TO ANSWER HERE - WILL STOP WHEN SET TO FALSE
var junk = setTimeout('myRepeatingImageLoader();', 6000); //Repeat again
}
function loadNewSet(){
gKeepRunning == false; //KEY TO ANSWER HERE
loadImages();
}
Found the anwser here:
Javascript: Cancel/Stop Image Requests
if(window.stop !== undefined)
{
window.stop();
}
else if(document.execCommand !== undefined)
{
document.execCommand("Stop", false);
}

Categories

Resources