Javascript

JavaScript SetInterval() function tutorial with examples

JavaScript setInterval: Main Tips The JavaScript setInterval() method executes a specified function multiple times at set time intervals specified in milliseconds (1000ms = 1second). The JS setInterval() method will keep calling the specified function...

Written by Luci · 2 min read >

JavaScript setInterval: Main Tips

The JavaScript setInterval() method executes a specified function multiple times at set time intervals specified in milliseconds (1000ms = 1second).

The JS setInterval() method will keep calling the specified function until clearInterval() method is called or the window is closed.

The JavaScript setInterval() method returns an ID which can be used by the clearInterval() method to stop the interval.

If you only need to execute a function one time, use the setTimeout() method.

Usage of JavaScript setInterval

JavaScript interval to be set use setInterval() function. It could be defined simply as a method which allows you to invoke functions in set intervals.

The JS setInterval() function is similar to the setTimeout method. How are they different? Well, setTimeout() calls functions once. However, with the set interval method you can invoke them multiple times.

Let’s say you need to display a message to your website visitors every 3 seconds. By applying the JavaScript setInterval() function, you will be able to perform this task and incorporate a new feature on your website.

However, we would recommend not to overuse this function as it might disrupt the overall user experience. The following code example shows the way the message is set to be displayed every 3 seconds:

setInterval(() => {
  alert("Hello"); 
}, 3000);

Syntax to Follow

See the code snippet below. This is the syntax of the function that you should keep in mind:

setInterval(function, milliseconds, param_one, param_two, ...)

As you can see, the JavaScript setInterval() can contain three parameters. The first one identifies which function is going to be applied in the set time intervals. As you might expect, you also should include the milliseconds to set the frequency of your function. Additionally, you can specify parameters for the function to be applied.

ParameterDescription
functionRequired. Defines the function to run.
millisecondsRequired. Defines how often the function will be executed (in millisecond intervals).
param_one, param_two, …Not required. Defines any additional function parameters.

Note: Any interval defined to be shorter than 10 milliseconds will be automatically changed to 10.

Stopping the Function

In some cases, you might need to make JavaScript stop setInterval() from being executed before the times comes. You’ll need to use the clearInterval() method. It’s meant to stop the timer set by using the setInterval JavaScript function.

The setInterval() returns a variable called an interval ID. You can then use it to call the clearInterval() function, as it’s required by the syntax:

clearInterval(intervalId);

clearInterval() itself has no return value: the only result is achieves is making JavaScript stop setInterval() from running.

Code Examples to Analyze

For a more productive learning experience, we include useful code examples that you can practice using the setInterval JavaScript function.

The example below displays a popup alert every 2 seconds:

var myVar;
function myFunction() {
  myVar = setInterval(every2sec, 2000);
}

function every2sec() { 
  alert("Alert Text!"); 
}
myFunction();

Now, this next example finds an HTML element with an ID clock, and changes its text to show the current time every second. In other words, it works like a digital clock:

var idVar = setInterval(() => { 
   timer()
}, 1000);

function timer() {
   var dateVar = new Date();
   var time = dateVar.toLocaleTimeString();
   document.getElementById("clock").innerHTML = time;
};

While this next example works exactly like the one above, it has a stopMyFunction method. If you ran the function, it would stop the clock:

You can you use the code in the example below to modify the width of a specified element until it’s exactly 100px wide:

function move() {  
  var elem = document.getElementById("moveBar");   
  var width = 0;  
  var idVar = setInterval(change, 10);  

function change() {    
  if (width == 100){
     clearInterval(idVar)
  } 
  else {      
     width++;        
     elem.style.width = width + '%';      
  }  
 }
}

Our last example toggles the background color from lime to red until the stopColor function is executed:

var idVar = setInterval(() => { 
  setColor() 
}, 400);

function setColor() {    
  var x = document.body;    
  x.style.backgroundColor = x.style.backgroundColor == "blue" ? "red" : "blue";
}

function stopColor() {
  clearInterval(idVar);
}

Get the Max/Min date in an array of objects in JavaScript

Luci in Javascript
  ·   3 min read

Filter an array of objects based on a property – JavaScript

Luci in Javascript
  ·   2 min read

Update an object’s property in array of objects in JS

Luci in Javascript
  ·   5 min read
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment. x
()
x
| Reply

资讯网周易 pdf儿童起名字大全女孩子免费猪猪宝宝起名禁忌吗丰台周边网站建设深圳外贸网站建设规划卖手表的公司起名农家丑妻用林起网名河南商丘的历史姓姓崔取名起名大全诗经公司起名公司起名网取名宋词起名 女孩人名涂惠源百万庄附近美食在线算命免费事业关于抗疫的诗词完整网站制作教程算命先生准的周公解梦泥路悲惨世界第一章读后感外贸b2c网站建设北京外贸网站SEO回到三国的无敌特种兵画室起名自助建站网站建设如何刷seo关键词排名龙凤双胞胎起什么名字好建设一个网站一般要多少钱青岛卫视少年生前被连续抽血16次?多部门介入两大学生合买彩票中奖一人不认账让美丽中国“从细节出发”淀粉肠小王子日销售额涨超10倍高中生被打伤下体休学 邯郸通报单亲妈妈陷入热恋 14岁儿子报警何赛飞追着代拍打雅江山火三名扑火人员牺牲系谣言张家界的山上“长”满了韩国人?男孩8年未见母亲被告知被遗忘中国拥有亿元资产的家庭达13.3万户19岁小伙救下5人后溺亡 多方发声315晚会后胖东来又人满为患了张立群任西安交通大学校长“重生之我在北大当嫡校长”男子被猫抓伤后确诊“猫抓病”测试车高速逃费 小米:已补缴周杰伦一审败诉网易网友洛杉矶偶遇贾玲今日春分倪萍分享减重40斤方法七年后宇文玥被薅头发捞上岸许家印被限制高消费萧美琴窜访捷克 外交部回应联合利华开始重组专访95后高颜值猪保姆胖东来员工每周单休无小长假男子被流浪猫绊倒 投喂者赔24万小米汽车超级工厂正式揭幕黑马情侣提车了西双版纳热带植物园回应蜉蝣大爆发当地回应沈阳致3死车祸车主疑毒驾恒大被罚41.75亿到底怎么缴妈妈回应孩子在校撞护栏坠楼外国人感慨凌晨的中国很安全杨倩无缘巴黎奥运校方回应护栏损坏小学生课间坠楼房客欠租失踪 房东直发愁专家建议不必谈骨泥色变王树国卸任西安交大校长 师生送别手机成瘾是影响睡眠质量重要因素国产伟哥去年销售近13亿阿根廷将发行1万与2万面值的纸币兔狲“狲大娘”因病死亡遭遇山火的松茸之乡“开封王婆”爆火:促成四五十对奥巴马现身唐宁街 黑色着装引猜测考生莫言也上北大硕士复试名单了德国打算提及普京时仅用姓名天水麻辣烫把捣辣椒大爷累坏了

资讯网 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化