JavaScript - Do something every n seconds [duplicate]

流过昼夜 提交于 2020-11-27 05:53:21

问题


I am fairly new to JavaScript, and I am learning it through p5 and videos by Daniel Shiffman.

I've been looking for a way to update a program every minute or so that checks a weather api, so I don't have to refresh the page myself.

I am aware that there are already answers to this question on here, but none of them make sense to me, as I am very new to JS.

So if you could answer it with an ELI5 ("Explain it like I'm five") description that would great.


回答1:


setInterval() is your easiest option.

Take a look at this simple example:

// Will execute myCallback every 0.5 seconds 
var intervalID = window.setInterval(myCallback, 500);

function myCallback() {
 // Your code here
}

More information and more examples can be found here: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval (https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval)




回答2:


In plain vanilla Javascript, you would use setInterval:

var intervalID = window.setInterval(checkWeatherAPI, 60000);

function checkWeatherAPI() {
  // go check API 
  console.log("checking weather API");
}

If you were to run the above, the callback function: checkWeatherAPI, would run once every minute, or 60,000 milliseconds forever, full documentation here: WindwTimers.setInterval

To stop the interval you would simply run this line:

window.clearInterval(intervalID);



回答3:


Choosing whether setInterval OR setTimeout is based on your need and requirement as explained a bit about the difference below.

setInterval will be called irrespective of the time taken by the API. For an instance you set an API call every 5 seconds and your API call is taking 6 seconds due to the network latency or server latency, the below setInterval will trigger the second API call before the first API completes.

var timer = setInterval(callAPI, 5000);

function callAPI() {
  // TO DO
  triggerXhrRequest(function(success){

  });
}

Instead, if you want to trigger another API call after 5 seconds once the first API call completed, you can better use setTimeout as below.

var timer = setTimeout(callAPI, 5000);

function callAPI() {
  // TO DO
  triggerXhrRequest(function(success){
      timer = setTimeout(callAPI, 5000);
  });
}

setTimeout will be called once after nth seconds. So you can control when the next one can be called as above.

MDN Documentation

setTimeout

setInterval




回答4:


function doThings() {
   //the things i want to happen (or increment)
}

setTimeout(function() {
    doThings();
}, 1000);//milliseconds


来源:https://stackoverflow.com/questions/40711300/javascript-do-something-every-n-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!