termitek12
termitek12

Reputation: 11

Javascript: Call a function again after specific time period

what if I want to run function immediately at first (onclick) but later I want set timeout to 3 second on every onclick before it's run ? Any ideas?

function FetchData() {
}

EDIT: @epascarello code did exactly the thing I wanted it to do.

BTW is there any way to delete 'old' messages when clicking on a button BUT not delete all div content - only the things that were added by this onclick function (old ones so only the newest message will occur)?

Upvotes: 0

Views: 801

Answers (4)

Mensur Grišević
Mensur Grišević

Reputation: 593

try this:

var first = true;

function FetchData() {
    if(first) {
       //magic
       first = false;
    } else {
       window.setTimeout(function() {
         //magic
       }, 3000);
    }
}

Upvotes: 0

fedeghe
fedeghe

Reputation: 1318

You could use something like h as handler:

function h(){
  //
  // do Your code
  //
  h.to = h.to ?
    clearTimeout(h.to)
    :
    setTimeout(h, 3000);
}

https://jsfiddle.net/vfLo4htd/

Upvotes: 1

epascarello
epascarello

Reputation: 207501

So listen for the first click and call the function, after that flip a boolean and set the delay.

(function(){

  var _first = true,
      timer;
  
  function FetchData() {
      var delay = _first ? 0 : 3000;
      if (timer) window.clearTimeout(timer);
      timer = window.setTimeout(_runFetch, delay);
      _first = false;
  }

  /* Or you can do if a few microseconds matter
  function FetchData() {
      if (_first) {
          _runFetch() 
          _first = false;
      } else {
          if (timer) window.clearTimeout(timer);
          timer = window.setTimeout(_runFetch, 3000);
      }
  }

  */
      
  function _runFetch() {
      var out = document.getElementById("out");
      out.innerHTML = (new Date()) + "<br/>" + out.innerHTML;
  }
  
  
  document.getElementById("btn").addEventListener("click", FetchData);
  
}());
<button id="btn">Click</button>
<div id="out"></div>

Upvotes: 0

Rajesh
Rajesh

Reputation: 24915

You can have a flag to check if its first click or not. Credits @epascarello

var timeout = null;
var firstClick = false;

function notify() {
  console.log("Hello World!");
}

function clickHandler() {
  if(!firstClick){
    firstClick = true;
    notify();
    return true;
  }
  
  if (timeout) {
    resetTimeout();
  } 
  initTimeout();
}

function initTimeout() {
  timeout = setTimeout(notify, 3000);
}

function resetTimeout() {
  window.clearTimeout(timeout);
  timeout = null
}
<button onclick="clickHandler()">Click me!!!</button>

Upvotes: 0

Related Questions