Home > Software engineering >  How to pass a parameters under onload function?
How to pass a parameters under onload function?

Time:03-17

<body onl oad="startTime('<%= time %>')">

</body>

<script>
  setTimeout(function startTime(time) {

    alert(time);
  }, 1000) 
</script>

I have returned the "time" from the client side by input from another page. Then, the "startTime()" will be called each seconds, in which the "time" parameter will be given to the function.

How can I pass the "time" variable in the <script> in every seconds under the onl oad function.

CodePudding user response:

Though your question isn't much clear, maybe you can use $('document').ready(function(){}); inside your script if you use jQuery. Also if you don't want to use jQuery another approach might be self executing anonymous function like this

<script>
(function(time) {
  //this function will we invoked immediately
  console.log(time);
})("Pass params here");
</script>

CodePudding user response:

setTimeout will run the function after the timer (in your case 1000ms) has run out. If you want it to continuously run every N seconds, you need to use setInterval instead.

MDN: https://developer.mozilla.org/en-US/docs/Web/API/setInterval

You can pass arguments to the callback function, by passing a 3rd (or more) argument to the setInterval. But it won't be updated, you need to build your own code around it, so you get the updated value.

What you have in your code right now will not work. You don't call the callback function directly. setTimeout starts immediately after the page loads. Your startTime function is anonymous, and is essentially this:

  setTimeout((time)  => {
    alert(time);
  }, 1000) 
// alert will be run after 1 second on page load

Another recommendation is, to not run code from HTML strings. Keep JavaScript related code inside of JavaScript. You can query HTML Elements inside of JavaScript and depending on if they changed, you can start running the code.

CodePudding user response:

For running it every second, you have to use setInterval instead of setTimeout.

You should introduce your startTime outside of setInterval.

Your '<%= time %>' should not be a string too, it should be like this <body onl oad="startTime(<%= time %>)">.

<body onl oad="startTime(1000)">

</body>

<script>
  function startTime(time) {
    setInterval(function() {
      alert(time);
    }, time)
  }
</script>

If time is a string you need to parse your time to a number.

<body onl oad="startTime('1000')">

</body>

<script>
  function startTime(time) {
    setInterval(function() {
      alert(time);
    }, Number(time)) //parse time string to a number
  }
</script>

  • Related