简体   繁体   中英

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)?

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/

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> 

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> 

try this:

var first = true;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM