How to call a function only for the first time - JavaScript









up vote
5
down vote

favorite
1












Note: I need to achieve this with pure javascript, I know there is a .one() method in jquery to do this, but I need the same output in pure javascript.



Scenario: I am trying to call a function when a user scrolls and reaches to the 3/4 part or more of the page, but the problem rises when user reaches that part, We all know they can't be pixel perfect so, after the condition is met, the function gets executed per pixel scroll.



I want that to execute only once the condition is met, then add a section at the bottom of the page, and then again user should reach the bottom and the function should get executed only once and so on...



Snippet:






var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];

var addPage = function()
var page = document.createElement('div');
page.classList.add('page');
page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
document.body.append(page);
console.log('added a new page');


var scrollAndAdd = function()
if (window.scrollY < (window.innerHeight * (3 / 4)))
// execute addPage only once for each attempt; it's creating infinite pages
addPage();



window.addEventListener('scroll', scrollAndAdd);

* 
margin: 0;
padding: 0;


.page
height: 100vh;

<div class='page' style='background-color: lightgreen'></div>
<div class='page' style='background-color: skyblue'></div>












share|improve this question

















  • 2




    So you will need to remember that you executed your method. Add a global variable and reset when the extra page is added
    – Hans Kesting
    Nov 11 at 19:54










  • Do you only want one page to be added ever or is there a condition whereby another can be added again. Should the user first scroll up again, or what is the logic?
    – trincot
    Nov 11 at 19:59










  • @trincot let's say there are two pages, so the total height of the body should be 200vh (since 1 page is 100vh) , assuming user scrolled to 190vh and trying to scroll even below, then a new page is added, and the total body height is now 300vh, now user scrolls to 290vh and more and another page should be added and so on....
    – Towkir Ahmed
    Nov 11 at 20:01











  • Like @HansKesting says, if you need to remember page state, put that state into global variable(s) to read and update in your function. Define your state above the function in your script, and give it whatever initial values you want.
    – Dave S
    Nov 11 at 20:09











  • You can make the threshold used to determine if another page should be loaded dynamic. Since page size is fixed (100vh) l. So when you reach 190 update page with new content and add100 to your threshold, and now iff you past that line will a new page be loaded
    – Tony
    Nov 11 at 20:24














up vote
5
down vote

favorite
1












Note: I need to achieve this with pure javascript, I know there is a .one() method in jquery to do this, but I need the same output in pure javascript.



Scenario: I am trying to call a function when a user scrolls and reaches to the 3/4 part or more of the page, but the problem rises when user reaches that part, We all know they can't be pixel perfect so, after the condition is met, the function gets executed per pixel scroll.



I want that to execute only once the condition is met, then add a section at the bottom of the page, and then again user should reach the bottom and the function should get executed only once and so on...



Snippet:






var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];

var addPage = function()
var page = document.createElement('div');
page.classList.add('page');
page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
document.body.append(page);
console.log('added a new page');


var scrollAndAdd = function()
if (window.scrollY < (window.innerHeight * (3 / 4)))
// execute addPage only once for each attempt; it's creating infinite pages
addPage();



window.addEventListener('scroll', scrollAndAdd);

* 
margin: 0;
padding: 0;


.page
height: 100vh;

<div class='page' style='background-color: lightgreen'></div>
<div class='page' style='background-color: skyblue'></div>












share|improve this question

















  • 2




    So you will need to remember that you executed your method. Add a global variable and reset when the extra page is added
    – Hans Kesting
    Nov 11 at 19:54










  • Do you only want one page to be added ever or is there a condition whereby another can be added again. Should the user first scroll up again, or what is the logic?
    – trincot
    Nov 11 at 19:59










  • @trincot let's say there are two pages, so the total height of the body should be 200vh (since 1 page is 100vh) , assuming user scrolled to 190vh and trying to scroll even below, then a new page is added, and the total body height is now 300vh, now user scrolls to 290vh and more and another page should be added and so on....
    – Towkir Ahmed
    Nov 11 at 20:01











  • Like @HansKesting says, if you need to remember page state, put that state into global variable(s) to read and update in your function. Define your state above the function in your script, and give it whatever initial values you want.
    – Dave S
    Nov 11 at 20:09











  • You can make the threshold used to determine if another page should be loaded dynamic. Since page size is fixed (100vh) l. So when you reach 190 update page with new content and add100 to your threshold, and now iff you past that line will a new page be loaded
    – Tony
    Nov 11 at 20:24












up vote
5
down vote

favorite
1









up vote
5
down vote

favorite
1






1





Note: I need to achieve this with pure javascript, I know there is a .one() method in jquery to do this, but I need the same output in pure javascript.



Scenario: I am trying to call a function when a user scrolls and reaches to the 3/4 part or more of the page, but the problem rises when user reaches that part, We all know they can't be pixel perfect so, after the condition is met, the function gets executed per pixel scroll.



I want that to execute only once the condition is met, then add a section at the bottom of the page, and then again user should reach the bottom and the function should get executed only once and so on...



Snippet:






var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];

var addPage = function()
var page = document.createElement('div');
page.classList.add('page');
page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
document.body.append(page);
console.log('added a new page');


var scrollAndAdd = function()
if (window.scrollY < (window.innerHeight * (3 / 4)))
// execute addPage only once for each attempt; it's creating infinite pages
addPage();



window.addEventListener('scroll', scrollAndAdd);

* 
margin: 0;
padding: 0;


.page
height: 100vh;

<div class='page' style='background-color: lightgreen'></div>
<div class='page' style='background-color: skyblue'></div>












share|improve this question













Note: I need to achieve this with pure javascript, I know there is a .one() method in jquery to do this, but I need the same output in pure javascript.



Scenario: I am trying to call a function when a user scrolls and reaches to the 3/4 part or more of the page, but the problem rises when user reaches that part, We all know they can't be pixel perfect so, after the condition is met, the function gets executed per pixel scroll.



I want that to execute only once the condition is met, then add a section at the bottom of the page, and then again user should reach the bottom and the function should get executed only once and so on...



Snippet:






var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];

var addPage = function()
var page = document.createElement('div');
page.classList.add('page');
page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
document.body.append(page);
console.log('added a new page');


var scrollAndAdd = function()
if (window.scrollY < (window.innerHeight * (3 / 4)))
// execute addPage only once for each attempt; it's creating infinite pages
addPage();



window.addEventListener('scroll', scrollAndAdd);

* 
margin: 0;
padding: 0;


.page
height: 100vh;

<div class='page' style='background-color: lightgreen'></div>
<div class='page' style='background-color: skyblue'></div>








var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];

var addPage = function()
var page = document.createElement('div');
page.classList.add('page');
page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
document.body.append(page);
console.log('added a new page');


var scrollAndAdd = function()
if (window.scrollY < (window.innerHeight * (3 / 4)))
// execute addPage only once for each attempt; it's creating infinite pages
addPage();



window.addEventListener('scroll', scrollAndAdd);

* 
margin: 0;
padding: 0;


.page
height: 100vh;

<div class='page' style='background-color: lightgreen'></div>
<div class='page' style='background-color: skyblue'></div>





var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];

var addPage = function()
var page = document.createElement('div');
page.classList.add('page');
page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
document.body.append(page);
console.log('added a new page');


var scrollAndAdd = function()
if (window.scrollY < (window.innerHeight * (3 / 4)))
// execute addPage only once for each attempt; it's creating infinite pages
addPage();



window.addEventListener('scroll', scrollAndAdd);

* 
margin: 0;
padding: 0;


.page
height: 100vh;

<div class='page' style='background-color: lightgreen'></div>
<div class='page' style='background-color: skyblue'></div>






javascript






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 11 at 19:49









Towkir Ahmed

922619




922619







  • 2




    So you will need to remember that you executed your method. Add a global variable and reset when the extra page is added
    – Hans Kesting
    Nov 11 at 19:54










  • Do you only want one page to be added ever or is there a condition whereby another can be added again. Should the user first scroll up again, or what is the logic?
    – trincot
    Nov 11 at 19:59










  • @trincot let's say there are two pages, so the total height of the body should be 200vh (since 1 page is 100vh) , assuming user scrolled to 190vh and trying to scroll even below, then a new page is added, and the total body height is now 300vh, now user scrolls to 290vh and more and another page should be added and so on....
    – Towkir Ahmed
    Nov 11 at 20:01











  • Like @HansKesting says, if you need to remember page state, put that state into global variable(s) to read and update in your function. Define your state above the function in your script, and give it whatever initial values you want.
    – Dave S
    Nov 11 at 20:09











  • You can make the threshold used to determine if another page should be loaded dynamic. Since page size is fixed (100vh) l. So when you reach 190 update page with new content and add100 to your threshold, and now iff you past that line will a new page be loaded
    – Tony
    Nov 11 at 20:24












  • 2




    So you will need to remember that you executed your method. Add a global variable and reset when the extra page is added
    – Hans Kesting
    Nov 11 at 19:54










  • Do you only want one page to be added ever or is there a condition whereby another can be added again. Should the user first scroll up again, or what is the logic?
    – trincot
    Nov 11 at 19:59










  • @trincot let's say there are two pages, so the total height of the body should be 200vh (since 1 page is 100vh) , assuming user scrolled to 190vh and trying to scroll even below, then a new page is added, and the total body height is now 300vh, now user scrolls to 290vh and more and another page should be added and so on....
    – Towkir Ahmed
    Nov 11 at 20:01











  • Like @HansKesting says, if you need to remember page state, put that state into global variable(s) to read and update in your function. Define your state above the function in your script, and give it whatever initial values you want.
    – Dave S
    Nov 11 at 20:09











  • You can make the threshold used to determine if another page should be loaded dynamic. Since page size is fixed (100vh) l. So when you reach 190 update page with new content and add100 to your threshold, and now iff you past that line will a new page be loaded
    – Tony
    Nov 11 at 20:24







2




2




So you will need to remember that you executed your method. Add a global variable and reset when the extra page is added
– Hans Kesting
Nov 11 at 19:54




So you will need to remember that you executed your method. Add a global variable and reset when the extra page is added
– Hans Kesting
Nov 11 at 19:54












Do you only want one page to be added ever or is there a condition whereby another can be added again. Should the user first scroll up again, or what is the logic?
– trincot
Nov 11 at 19:59




Do you only want one page to be added ever or is there a condition whereby another can be added again. Should the user first scroll up again, or what is the logic?
– trincot
Nov 11 at 19:59












@trincot let's say there are two pages, so the total height of the body should be 200vh (since 1 page is 100vh) , assuming user scrolled to 190vh and trying to scroll even below, then a new page is added, and the total body height is now 300vh, now user scrolls to 290vh and more and another page should be added and so on....
– Towkir Ahmed
Nov 11 at 20:01





@trincot let's say there are two pages, so the total height of the body should be 200vh (since 1 page is 100vh) , assuming user scrolled to 190vh and trying to scroll even below, then a new page is added, and the total body height is now 300vh, now user scrolls to 290vh and more and another page should be added and so on....
– Towkir Ahmed
Nov 11 at 20:01













Like @HansKesting says, if you need to remember page state, put that state into global variable(s) to read and update in your function. Define your state above the function in your script, and give it whatever initial values you want.
– Dave S
Nov 11 at 20:09





Like @HansKesting says, if you need to remember page state, put that state into global variable(s) to read and update in your function. Define your state above the function in your script, and give it whatever initial values you want.
– Dave S
Nov 11 at 20:09













You can make the threshold used to determine if another page should be loaded dynamic. Since page size is fixed (100vh) l. So when you reach 190 update page with new content and add100 to your threshold, and now iff you past that line will a new page be loaded
– Tony
Nov 11 at 20:24




You can make the threshold used to determine if another page should be loaded dynamic. Since page size is fixed (100vh) l. So when you reach 190 update page with new content and add100 to your threshold, and now iff you past that line will a new page be loaded
– Tony
Nov 11 at 20:24












3 Answers
3






active

oldest

votes

















up vote
4
down vote



accepted










You don't really need logic to run the function just once; instead, use a different expression to determine whether to add the page. Once the page is added that same expression should no longer evaluate to true until more scrolling is done.



NB: I also changed a bit the random pick logic.






var colors = ['powderblue', 'lightgreen', 'indigo', 'coral', 'skyblue'];

var addPage = function()
var page = document.createElement('div');
page.classList.add('page');
// Make sure the same color is not selected twice in sequence:
var colorIndex = Math.floor(Math.random() * (colors.length-1));
var color = colors.splice(colorIndex,1)[0];
colors.push(color);
page.style.backgroundColor = color;
document.body.append(page);


var scrollAndAdd = function()
if (window.scrollY > document.body.clientHeight - window.innerHeight - 10)
addPage();


window.addEventListener('scroll', scrollAndAdd);

* 
margin: 0;
padding: 0;


.page
height: 100vh;

<div class='page' style='background-color: lightgreen'></div>
<div class='page' style='background-color: skyblue'></div>








share|improve this answer






















  • Great answer, thanks :)
    – Towkir Ahmed
    Nov 12 at 6:46










  • check this line var colorIndex = Math.floor(Math.random() * (colors.lengt-1)); shouldn't it be length there ?
    – Towkir Ahmed
    Nov 12 at 6:48










  • I meant there is a typo, it should be length-1 not lengt-1
    – Towkir Ahmed
    Nov 12 at 7:13










  • Ah yes indeed :) Fixed.
    – trincot
    Nov 12 at 7:32











  • browsing Your answers It's one of my favorite enjoyable activities, here on SO
    – deblocker
    Nov 27 at 20:34


















up vote
0
down vote













I hope it will help you:






var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];

var addPage = function()
var page = document.createElement('div');
page.classList.add('page');
page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
document.body.append(page);
console.log('added a new page');


var scrollAndAdd = function()
var a = document.body.clientHeight - window.innerHeight * (5 / 4)
if (window.scrollY > a)
addPage();



window.addEventListener('scroll', scrollAndAdd);

* 
margin: 0;
padding: 0;


.page
height: 100vh;

<div class='page' style='background-color: lightgreen'></div>
<div class='page' style='background-color: skyblue'></div>








share|improve this answer






















  • this is exactly what I am facing, how is this different than what I provided ?
    – Towkir Ahmed
    Nov 12 at 6:45










  • @TowkirAhmed, please note that this is different. Look at variable a.
    – trincot
    Nov 12 at 7:35










  • I did, you're right, but the first time it did create too many pages just like mine, will upvote the answer.
    – Towkir Ahmed
    Nov 12 at 8:26










  • @trincot, thank you thant pointed that my code works correct, moreover, I posted it earlier than you ;)
    – qiAlex
    Nov 12 at 10:00











  • Indeed, @qiAlex, but it was a matter of seconds -- good ideas often surface at the same time ;-) I'll give you my vote.
    – trincot
    Nov 12 at 14:46


















up vote
0
down vote













Well how about curry it up with local flag.



var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];


const localCurry = function(func, immediateAction)
var flag;
return function()
var context = this, args = arguments;
var callNow = immediateAction && !flag;
flag = true;
if (callNow) func.apply(context, args);




var addPage = localCurry(function()
var page = document.createElement('div');
page.classList.add('page');
page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
document.body.append(page);
console.log('added a new page');
, true);

var scrollAndAdd = function()
var a = document.body.clientHeight - window.innerHeight * (5 / 4)
if (window.scrollY > a)
addPage();



window.addEventListener('scroll', scrollAndAdd);



Now you do have option to reset the flag based on timer or custom logic.






share|improve this answer




















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53252562%2fhow-to-call-a-function-only-for-the-first-time-javascript%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    4
    down vote



    accepted










    You don't really need logic to run the function just once; instead, use a different expression to determine whether to add the page. Once the page is added that same expression should no longer evaluate to true until more scrolling is done.



    NB: I also changed a bit the random pick logic.






    var colors = ['powderblue', 'lightgreen', 'indigo', 'coral', 'skyblue'];

    var addPage = function()
    var page = document.createElement('div');
    page.classList.add('page');
    // Make sure the same color is not selected twice in sequence:
    var colorIndex = Math.floor(Math.random() * (colors.length-1));
    var color = colors.splice(colorIndex,1)[0];
    colors.push(color);
    page.style.backgroundColor = color;
    document.body.append(page);


    var scrollAndAdd = function()
    if (window.scrollY > document.body.clientHeight - window.innerHeight - 10)
    addPage();


    window.addEventListener('scroll', scrollAndAdd);

    * 
    margin: 0;
    padding: 0;


    .page
    height: 100vh;

    <div class='page' style='background-color: lightgreen'></div>
    <div class='page' style='background-color: skyblue'></div>








    share|improve this answer






















    • Great answer, thanks :)
      – Towkir Ahmed
      Nov 12 at 6:46










    • check this line var colorIndex = Math.floor(Math.random() * (colors.lengt-1)); shouldn't it be length there ?
      – Towkir Ahmed
      Nov 12 at 6:48










    • I meant there is a typo, it should be length-1 not lengt-1
      – Towkir Ahmed
      Nov 12 at 7:13










    • Ah yes indeed :) Fixed.
      – trincot
      Nov 12 at 7:32











    • browsing Your answers It's one of my favorite enjoyable activities, here on SO
      – deblocker
      Nov 27 at 20:34















    up vote
    4
    down vote



    accepted










    You don't really need logic to run the function just once; instead, use a different expression to determine whether to add the page. Once the page is added that same expression should no longer evaluate to true until more scrolling is done.



    NB: I also changed a bit the random pick logic.






    var colors = ['powderblue', 'lightgreen', 'indigo', 'coral', 'skyblue'];

    var addPage = function()
    var page = document.createElement('div');
    page.classList.add('page');
    // Make sure the same color is not selected twice in sequence:
    var colorIndex = Math.floor(Math.random() * (colors.length-1));
    var color = colors.splice(colorIndex,1)[0];
    colors.push(color);
    page.style.backgroundColor = color;
    document.body.append(page);


    var scrollAndAdd = function()
    if (window.scrollY > document.body.clientHeight - window.innerHeight - 10)
    addPage();


    window.addEventListener('scroll', scrollAndAdd);

    * 
    margin: 0;
    padding: 0;


    .page
    height: 100vh;

    <div class='page' style='background-color: lightgreen'></div>
    <div class='page' style='background-color: skyblue'></div>








    share|improve this answer






















    • Great answer, thanks :)
      – Towkir Ahmed
      Nov 12 at 6:46










    • check this line var colorIndex = Math.floor(Math.random() * (colors.lengt-1)); shouldn't it be length there ?
      – Towkir Ahmed
      Nov 12 at 6:48










    • I meant there is a typo, it should be length-1 not lengt-1
      – Towkir Ahmed
      Nov 12 at 7:13










    • Ah yes indeed :) Fixed.
      – trincot
      Nov 12 at 7:32











    • browsing Your answers It's one of my favorite enjoyable activities, here on SO
      – deblocker
      Nov 27 at 20:34













    up vote
    4
    down vote



    accepted







    up vote
    4
    down vote



    accepted






    You don't really need logic to run the function just once; instead, use a different expression to determine whether to add the page. Once the page is added that same expression should no longer evaluate to true until more scrolling is done.



    NB: I also changed a bit the random pick logic.






    var colors = ['powderblue', 'lightgreen', 'indigo', 'coral', 'skyblue'];

    var addPage = function()
    var page = document.createElement('div');
    page.classList.add('page');
    // Make sure the same color is not selected twice in sequence:
    var colorIndex = Math.floor(Math.random() * (colors.length-1));
    var color = colors.splice(colorIndex,1)[0];
    colors.push(color);
    page.style.backgroundColor = color;
    document.body.append(page);


    var scrollAndAdd = function()
    if (window.scrollY > document.body.clientHeight - window.innerHeight - 10)
    addPage();


    window.addEventListener('scroll', scrollAndAdd);

    * 
    margin: 0;
    padding: 0;


    .page
    height: 100vh;

    <div class='page' style='background-color: lightgreen'></div>
    <div class='page' style='background-color: skyblue'></div>








    share|improve this answer














    You don't really need logic to run the function just once; instead, use a different expression to determine whether to add the page. Once the page is added that same expression should no longer evaluate to true until more scrolling is done.



    NB: I also changed a bit the random pick logic.






    var colors = ['powderblue', 'lightgreen', 'indigo', 'coral', 'skyblue'];

    var addPage = function()
    var page = document.createElement('div');
    page.classList.add('page');
    // Make sure the same color is not selected twice in sequence:
    var colorIndex = Math.floor(Math.random() * (colors.length-1));
    var color = colors.splice(colorIndex,1)[0];
    colors.push(color);
    page.style.backgroundColor = color;
    document.body.append(page);


    var scrollAndAdd = function()
    if (window.scrollY > document.body.clientHeight - window.innerHeight - 10)
    addPage();


    window.addEventListener('scroll', scrollAndAdd);

    * 
    margin: 0;
    padding: 0;


    .page
    height: 100vh;

    <div class='page' style='background-color: lightgreen'></div>
    <div class='page' style='background-color: skyblue'></div>








    var colors = ['powderblue', 'lightgreen', 'indigo', 'coral', 'skyblue'];

    var addPage = function()
    var page = document.createElement('div');
    page.classList.add('page');
    // Make sure the same color is not selected twice in sequence:
    var colorIndex = Math.floor(Math.random() * (colors.length-1));
    var color = colors.splice(colorIndex,1)[0];
    colors.push(color);
    page.style.backgroundColor = color;
    document.body.append(page);


    var scrollAndAdd = function()
    if (window.scrollY > document.body.clientHeight - window.innerHeight - 10)
    addPage();


    window.addEventListener('scroll', scrollAndAdd);

    * 
    margin: 0;
    padding: 0;


    .page
    height: 100vh;

    <div class='page' style='background-color: lightgreen'></div>
    <div class='page' style='background-color: skyblue'></div>





    var colors = ['powderblue', 'lightgreen', 'indigo', 'coral', 'skyblue'];

    var addPage = function()
    var page = document.createElement('div');
    page.classList.add('page');
    // Make sure the same color is not selected twice in sequence:
    var colorIndex = Math.floor(Math.random() * (colors.length-1));
    var color = colors.splice(colorIndex,1)[0];
    colors.push(color);
    page.style.backgroundColor = color;
    document.body.append(page);


    var scrollAndAdd = function()
    if (window.scrollY > document.body.clientHeight - window.innerHeight - 10)
    addPage();


    window.addEventListener('scroll', scrollAndAdd);

    * 
    margin: 0;
    padding: 0;


    .page
    height: 100vh;

    <div class='page' style='background-color: lightgreen'></div>
    <div class='page' style='background-color: skyblue'></div>






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 12 at 7:33

























    answered Nov 11 at 20:13









    trincot

    115k1478109




    115k1478109











    • Great answer, thanks :)
      – Towkir Ahmed
      Nov 12 at 6:46










    • check this line var colorIndex = Math.floor(Math.random() * (colors.lengt-1)); shouldn't it be length there ?
      – Towkir Ahmed
      Nov 12 at 6:48










    • I meant there is a typo, it should be length-1 not lengt-1
      – Towkir Ahmed
      Nov 12 at 7:13










    • Ah yes indeed :) Fixed.
      – trincot
      Nov 12 at 7:32











    • browsing Your answers It's one of my favorite enjoyable activities, here on SO
      – deblocker
      Nov 27 at 20:34

















    • Great answer, thanks :)
      – Towkir Ahmed
      Nov 12 at 6:46










    • check this line var colorIndex = Math.floor(Math.random() * (colors.lengt-1)); shouldn't it be length there ?
      – Towkir Ahmed
      Nov 12 at 6:48










    • I meant there is a typo, it should be length-1 not lengt-1
      – Towkir Ahmed
      Nov 12 at 7:13










    • Ah yes indeed :) Fixed.
      – trincot
      Nov 12 at 7:32











    • browsing Your answers It's one of my favorite enjoyable activities, here on SO
      – deblocker
      Nov 27 at 20:34
















    Great answer, thanks :)
    – Towkir Ahmed
    Nov 12 at 6:46




    Great answer, thanks :)
    – Towkir Ahmed
    Nov 12 at 6:46












    check this line var colorIndex = Math.floor(Math.random() * (colors.lengt-1)); shouldn't it be length there ?
    – Towkir Ahmed
    Nov 12 at 6:48




    check this line var colorIndex = Math.floor(Math.random() * (colors.lengt-1)); shouldn't it be length there ?
    – Towkir Ahmed
    Nov 12 at 6:48












    I meant there is a typo, it should be length-1 not lengt-1
    – Towkir Ahmed
    Nov 12 at 7:13




    I meant there is a typo, it should be length-1 not lengt-1
    – Towkir Ahmed
    Nov 12 at 7:13












    Ah yes indeed :) Fixed.
    – trincot
    Nov 12 at 7:32





    Ah yes indeed :) Fixed.
    – trincot
    Nov 12 at 7:32













    browsing Your answers It's one of my favorite enjoyable activities, here on SO
    – deblocker
    Nov 27 at 20:34





    browsing Your answers It's one of my favorite enjoyable activities, here on SO
    – deblocker
    Nov 27 at 20:34













    up vote
    0
    down vote













    I hope it will help you:






    var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];

    var addPage = function()
    var page = document.createElement('div');
    page.classList.add('page');
    page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
    document.body.append(page);
    console.log('added a new page');


    var scrollAndAdd = function()
    var a = document.body.clientHeight - window.innerHeight * (5 / 4)
    if (window.scrollY > a)
    addPage();



    window.addEventListener('scroll', scrollAndAdd);

    * 
    margin: 0;
    padding: 0;


    .page
    height: 100vh;

    <div class='page' style='background-color: lightgreen'></div>
    <div class='page' style='background-color: skyblue'></div>








    share|improve this answer






















    • this is exactly what I am facing, how is this different than what I provided ?
      – Towkir Ahmed
      Nov 12 at 6:45










    • @TowkirAhmed, please note that this is different. Look at variable a.
      – trincot
      Nov 12 at 7:35










    • I did, you're right, but the first time it did create too many pages just like mine, will upvote the answer.
      – Towkir Ahmed
      Nov 12 at 8:26










    • @trincot, thank you thant pointed that my code works correct, moreover, I posted it earlier than you ;)
      – qiAlex
      Nov 12 at 10:00











    • Indeed, @qiAlex, but it was a matter of seconds -- good ideas often surface at the same time ;-) I'll give you my vote.
      – trincot
      Nov 12 at 14:46















    up vote
    0
    down vote













    I hope it will help you:






    var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];

    var addPage = function()
    var page = document.createElement('div');
    page.classList.add('page');
    page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
    document.body.append(page);
    console.log('added a new page');


    var scrollAndAdd = function()
    var a = document.body.clientHeight - window.innerHeight * (5 / 4)
    if (window.scrollY > a)
    addPage();



    window.addEventListener('scroll', scrollAndAdd);

    * 
    margin: 0;
    padding: 0;


    .page
    height: 100vh;

    <div class='page' style='background-color: lightgreen'></div>
    <div class='page' style='background-color: skyblue'></div>








    share|improve this answer






















    • this is exactly what I am facing, how is this different than what I provided ?
      – Towkir Ahmed
      Nov 12 at 6:45










    • @TowkirAhmed, please note that this is different. Look at variable a.
      – trincot
      Nov 12 at 7:35










    • I did, you're right, but the first time it did create too many pages just like mine, will upvote the answer.
      – Towkir Ahmed
      Nov 12 at 8:26










    • @trincot, thank you thant pointed that my code works correct, moreover, I posted it earlier than you ;)
      – qiAlex
      Nov 12 at 10:00











    • Indeed, @qiAlex, but it was a matter of seconds -- good ideas often surface at the same time ;-) I'll give you my vote.
      – trincot
      Nov 12 at 14:46













    up vote
    0
    down vote










    up vote
    0
    down vote









    I hope it will help you:






    var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];

    var addPage = function()
    var page = document.createElement('div');
    page.classList.add('page');
    page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
    document.body.append(page);
    console.log('added a new page');


    var scrollAndAdd = function()
    var a = document.body.clientHeight - window.innerHeight * (5 / 4)
    if (window.scrollY > a)
    addPage();



    window.addEventListener('scroll', scrollAndAdd);

    * 
    margin: 0;
    padding: 0;


    .page
    height: 100vh;

    <div class='page' style='background-color: lightgreen'></div>
    <div class='page' style='background-color: skyblue'></div>








    share|improve this answer














    I hope it will help you:






    var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];

    var addPage = function()
    var page = document.createElement('div');
    page.classList.add('page');
    page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
    document.body.append(page);
    console.log('added a new page');


    var scrollAndAdd = function()
    var a = document.body.clientHeight - window.innerHeight * (5 / 4)
    if (window.scrollY > a)
    addPage();



    window.addEventListener('scroll', scrollAndAdd);

    * 
    margin: 0;
    padding: 0;


    .page
    height: 100vh;

    <div class='page' style='background-color: lightgreen'></div>
    <div class='page' style='background-color: skyblue'></div>








    var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];

    var addPage = function()
    var page = document.createElement('div');
    page.classList.add('page');
    page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
    document.body.append(page);
    console.log('added a new page');


    var scrollAndAdd = function()
    var a = document.body.clientHeight - window.innerHeight * (5 / 4)
    if (window.scrollY > a)
    addPage();



    window.addEventListener('scroll', scrollAndAdd);

    * 
    margin: 0;
    padding: 0;


    .page
    height: 100vh;

    <div class='page' style='background-color: lightgreen'></div>
    <div class='page' style='background-color: skyblue'></div>





    var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];

    var addPage = function()
    var page = document.createElement('div');
    page.classList.add('page');
    page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
    document.body.append(page);
    console.log('added a new page');


    var scrollAndAdd = function()
    var a = document.body.clientHeight - window.innerHeight * (5 / 4)
    if (window.scrollY > a)
    addPage();



    window.addEventListener('scroll', scrollAndAdd);

    * 
    margin: 0;
    padding: 0;


    .page
    height: 100vh;

    <div class='page' style='background-color: lightgreen'></div>
    <div class='page' style='background-color: skyblue'></div>






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 12 at 9:53

























    answered Nov 11 at 20:12









    qiAlex

    2,0301724




    2,0301724











    • this is exactly what I am facing, how is this different than what I provided ?
      – Towkir Ahmed
      Nov 12 at 6:45










    • @TowkirAhmed, please note that this is different. Look at variable a.
      – trincot
      Nov 12 at 7:35










    • I did, you're right, but the first time it did create too many pages just like mine, will upvote the answer.
      – Towkir Ahmed
      Nov 12 at 8:26










    • @trincot, thank you thant pointed that my code works correct, moreover, I posted it earlier than you ;)
      – qiAlex
      Nov 12 at 10:00











    • Indeed, @qiAlex, but it was a matter of seconds -- good ideas often surface at the same time ;-) I'll give you my vote.
      – trincot
      Nov 12 at 14:46

















    • this is exactly what I am facing, how is this different than what I provided ?
      – Towkir Ahmed
      Nov 12 at 6:45










    • @TowkirAhmed, please note that this is different. Look at variable a.
      – trincot
      Nov 12 at 7:35










    • I did, you're right, but the first time it did create too many pages just like mine, will upvote the answer.
      – Towkir Ahmed
      Nov 12 at 8:26










    • @trincot, thank you thant pointed that my code works correct, moreover, I posted it earlier than you ;)
      – qiAlex
      Nov 12 at 10:00











    • Indeed, @qiAlex, but it was a matter of seconds -- good ideas often surface at the same time ;-) I'll give you my vote.
      – trincot
      Nov 12 at 14:46
















    this is exactly what I am facing, how is this different than what I provided ?
    – Towkir Ahmed
    Nov 12 at 6:45




    this is exactly what I am facing, how is this different than what I provided ?
    – Towkir Ahmed
    Nov 12 at 6:45












    @TowkirAhmed, please note that this is different. Look at variable a.
    – trincot
    Nov 12 at 7:35




    @TowkirAhmed, please note that this is different. Look at variable a.
    – trincot
    Nov 12 at 7:35












    I did, you're right, but the first time it did create too many pages just like mine, will upvote the answer.
    – Towkir Ahmed
    Nov 12 at 8:26




    I did, you're right, but the first time it did create too many pages just like mine, will upvote the answer.
    – Towkir Ahmed
    Nov 12 at 8:26












    @trincot, thank you thant pointed that my code works correct, moreover, I posted it earlier than you ;)
    – qiAlex
    Nov 12 at 10:00





    @trincot, thank you thant pointed that my code works correct, moreover, I posted it earlier than you ;)
    – qiAlex
    Nov 12 at 10:00













    Indeed, @qiAlex, but it was a matter of seconds -- good ideas often surface at the same time ;-) I'll give you my vote.
    – trincot
    Nov 12 at 14:46





    Indeed, @qiAlex, but it was a matter of seconds -- good ideas often surface at the same time ;-) I'll give you my vote.
    – trincot
    Nov 12 at 14:46











    up vote
    0
    down vote













    Well how about curry it up with local flag.



    var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];


    const localCurry = function(func, immediateAction)
    var flag;
    return function()
    var context = this, args = arguments;
    var callNow = immediateAction && !flag;
    flag = true;
    if (callNow) func.apply(context, args);




    var addPage = localCurry(function()
    var page = document.createElement('div');
    page.classList.add('page');
    page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
    document.body.append(page);
    console.log('added a new page');
    , true);

    var scrollAndAdd = function()
    var a = document.body.clientHeight - window.innerHeight * (5 / 4)
    if (window.scrollY > a)
    addPage();



    window.addEventListener('scroll', scrollAndAdd);



    Now you do have option to reset the flag based on timer or custom logic.






    share|improve this answer
























      up vote
      0
      down vote













      Well how about curry it up with local flag.



      var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];


      const localCurry = function(func, immediateAction)
      var flag;
      return function()
      var context = this, args = arguments;
      var callNow = immediateAction && !flag;
      flag = true;
      if (callNow) func.apply(context, args);




      var addPage = localCurry(function()
      var page = document.createElement('div');
      page.classList.add('page');
      page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
      document.body.append(page);
      console.log('added a new page');
      , true);

      var scrollAndAdd = function()
      var a = document.body.clientHeight - window.innerHeight * (5 / 4)
      if (window.scrollY > a)
      addPage();



      window.addEventListener('scroll', scrollAndAdd);



      Now you do have option to reset the flag based on timer or custom logic.






      share|improve this answer






















        up vote
        0
        down vote










        up vote
        0
        down vote









        Well how about curry it up with local flag.



        var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];


        const localCurry = function(func, immediateAction)
        var flag;
        return function()
        var context = this, args = arguments;
        var callNow = immediateAction && !flag;
        flag = true;
        if (callNow) func.apply(context, args);




        var addPage = localCurry(function()
        var page = document.createElement('div');
        page.classList.add('page');
        page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
        document.body.append(page);
        console.log('added a new page');
        , true);

        var scrollAndAdd = function()
        var a = document.body.clientHeight - window.innerHeight * (5 / 4)
        if (window.scrollY > a)
        addPage();



        window.addEventListener('scroll', scrollAndAdd);



        Now you do have option to reset the flag based on timer or custom logic.






        share|improve this answer












        Well how about curry it up with local flag.



        var colors = ['skyblue', 'powderblue', 'lightgreen', 'indigo', 'coral'];


        const localCurry = function(func, immediateAction)
        var flag;
        return function()
        var context = this, args = arguments;
        var callNow = immediateAction && !flag;
        flag = true;
        if (callNow) func.apply(context, args);




        var addPage = localCurry(function()
        var page = document.createElement('div');
        page.classList.add('page');
        page.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
        document.body.append(page);
        console.log('added a new page');
        , true);

        var scrollAndAdd = function()
        var a = document.body.clientHeight - window.innerHeight * (5 / 4)
        if (window.scrollY > a)
        addPage();



        window.addEventListener('scroll', scrollAndAdd);



        Now you do have option to reset the flag based on timer or custom logic.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 at 6:25









        Shubham Gautam

        20925




        20925



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53252562%2fhow-to-call-a-function-only-for-the-first-time-javascript%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            How to read a connectionString WITH PROVIDER in .NET Core?

            In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

            Museum of Modern and Contemporary Art of Trento and Rovereto