{"id":5536,"date":"2022-01-16T00:00:59","date_gmt":"2022-01-16T00:00:59","guid":{"rendered":"https:\/\/code-boxx.com\/?p=5536"},"modified":"2023-10-15T05:09:50","modified_gmt":"2023-10-15T05:09:50","slug":"pause-javascript","status":"publish","type":"post","link":"https:\/\/code-boxx.com\/pause-javascript\/","title":{"rendered":"3 Ways To Pause Javascript (Very Simple Examples)"},"content":{"rendered":"<p>Welcome to a quick tutorial on how to pause in Javascript. Bad news, there are no native implementations of pause in Javascript. But we can simulate pause, wait, sleep, or delay in Javascript via various means:<\/p>\n<div class=\"sec-head answer\">\n<ul>\n<li>Loop until a certain time has passed &#8211; <code>var now = Date.now(), end = now + 1000; while (now &lt; end) { now = Date.now(); }<\/code><\/li>\n<li><span style=\"vertical-align: inherit;\"><span style=\"vertical-align: inherit;\">Delay a function using timeout &#8211;<\/span><\/span>\u00a0<code>setTimeout(FUNCTION, 1000);<\/code><\/li>\n<li><span style=\"vertical-align: inherit;\"><span style=\"vertical-align: inherit;\">Delay the return of an async function &#8211;<\/span><\/span><code>async function fn () { await new Promise(res =&gt; setTimeout(res, 1000)); }<\/code><\/li>\n<\/ul>\n<\/div>\n<p>That covers the quick basics but read on for the detailed explanation &#8211; Also, for a possibly better solution.<\/p>\n<p>&nbsp;<\/p>\n<div id=\"ezoic-pub-ad-placeholder-101\"><\/div>\n<p>&nbsp;<\/p>\n<h2 class=\"in-head-d\">TABLE OF CONTENTS<\/h2>\n<div class=\"toc\">\n<div><a href=\"#sec-download\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/code-boxx.com\/wp-content\/uploads\/2019\/08\/ico-download.svg\" width=\"36\" height=\"36\" \/>Download &amp; Notes<\/a><\/div>\n<div><a href=\"#sec-pause\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/code-boxx.com\/wp-content\/uploads\/2019\/08\/ico-gear.svg\" width=\"36\" height=\"36\" \/>Javascript Pause<\/a><\/div>\n<div><a href=\"#sec-better\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/code-boxx.com\/wp-content\/uploads\/2019\/08\/ico-star.svg\" width=\"36\" height=\"36\" \/>A Possibly Better Way<\/a><\/div>\n<div><a href=\"#sec-extra\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/code-boxx.com\/wp-content\/uploads\/2019\/08\/ico-plus-square.svg\" width=\"36\" height=\"36\" \/>Extras<\/a><\/div>\n<div><a href=\"#sec-end\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/code-boxx.com\/wp-content\/uploads\/2019\/08\/ico-thumbs-up.svg\" width=\"36\" height=\"36\" \/>The End<\/a><\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<div id=\"sec-download\" class=\"sec-head\" style=\"background: #ffe8de;\">\n<h2 class=\"in-head-d\">DOWNLOAD &amp; NOTES<\/h2>\n<p>Here is the download link to the example code, so you don&#8217;t have to copy-paste everything.<\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #008000;\">EXAMPLE CODE DOWNLOAD<\/span><\/h3>\n<p><a href=\"https:\/\/gist.github.com\/code-boxx\/c6eabe0e96cb78aba269867ab1324667\" target=\"_blank\" rel=\"noopener noreferrer\">Source code on GitHub Gist<\/a><\/p>\n<p>Just click on &#8220;download zip&#8221; or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.<\/p>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #008000;\">SORRY FOR THE ADS...<\/span><\/h3>\r\n<p>But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a \"paid scripts\" business, and I don't \"block people with Adblock\". Every little bit of support helps.<\/p>\r\n\r\n<p><a class=\"ast-button\" href=\"https:\/\/www.paypal.com\/paypalme\/wstoh\/5\" target=\"_blank\" rel=\"nofollow noopener\">Buy Me A Coffee<\/a> <a class=\"ast-button\" href=\"https:\/\/payhip.com\/codeboxx\" target=\"_blank\" rel=\"nofollow noopener\">Code Boxx eBooks<\/a><\/p>\n<p>&nbsp;<\/p>\n<div id=\"ezoic-pub-ad-placeholder-102\"><\/div>\n<p>&nbsp;<\/p>\n<div id=\"sec-pause\" class=\"sec-head\" style=\"background: #e0f3ff;\">\n<h2 class=\"in-head-d\">JAVASCRIPT PAUSE<\/h2>\n<p>All right, let us get into the examples of possible ways to pause in Javascript.<\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #008000;\">TUTORIAL VIDEO<\/span><\/h3>\n<div class=\"ast-oembed-container \" style=\"height: 100%;\"><iframe loading=\"lazy\" title=\"3 Ways To Pause In Javascript\" width=\"500\" height=\"281\" src=\"https:\/\/www.youtube.com\/embed\/v214SDMgDPg?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/div>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #008000;\">METHOD 1) TIMESTAMP WHILE LOOP<\/span><\/h3>\n<div class=\"ref-head\">1-time-loop.html<\/div>\n<pre><code>\/\/ (A) DO SOMETHING\r\nconsole.log(\"First\");\r\n \r\n\/\/ (B) WAIT 2 SECONDS (2000 MS)\r\nvar now = Date.now(),\r\n    end = now + 2000;\r\nwhile (now &lt; end) { now = Date.now(); }\r\n \r\n\/\/ (C) PROCEED\r\nconsole.log(\"Second\");<\/code><\/pre>\n<p>For those who are lost:<\/p>\n<ul>\n<li><code>console.log(\"First\")<\/code>\u00a0will run first.<\/li>\n<li><code>now<\/code> is set to the current timestamp, and <code>end<\/code> is 2 seconds from now.<\/li>\n<li><code>while (now &lt; end) { now = Date.now(); }<\/code> will loop endlessly for 2 seconds, that&#8217;s our &#8220;pause&#8221;.<\/li>\n<li><code>console.log(\"Second\")<\/code> will run after 2 seconds.<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<div id=\"ezoic-pub-ad-placeholder-103\"><\/div>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #008000;\">METHOD 2) FUNCTION TIMEOUT<\/span><\/h3>\n<div class=\"ref-head\">2-timeout.html<\/div>\n<pre><code>\/\/ (A) FUNCTION TO RUN AFTER DELAY\r\nfunction demo () { console.log(\"Second\"); }\r\n \r\n\/\/ (B) DO SOMETHING\r\nconsole.log(\"First\");\r\n \r\n\/\/ (C) RUN DEMO() AFTER 2 SECONDS\r\nsetTimeout(demo, 2000);\r\n \r\n\/\/ (D) NOTE - TIMEOUT IS ASYNC, THIS WILL CONTINUE TO RUN!\r\nconsole.log(\"Third\");<\/code><\/pre>\n<ul>\n<li><strong>(A &amp; C)<\/strong> What is another way to emulate a &#8220;delay&#8221;? Just set the function in a good old timer &#8211; <code>setTimeout(FUNCTION, MS)<\/code>.<\/li>\n<li>But please take note extra note that <code>setTimeout()<\/code> is <strong><span style=\"text-decoration: underline;\">asynchronous<\/span><\/strong>.\n<ul style=\"list-style-type: circle;\">\n<li><code>console.log(\"First\")<\/code> will run first.<\/li>\n<li><code>setTimeout(demo, 2000)<\/code> will prime the function to run after 2 seconds.<\/li>\n<li><code>console.log(\"Third\")<\/code> will run next.<\/li>\n<li><code>demo()<\/code>\u00a0and <code>console.log(\"Second\")<\/code> will run after a 2 seconds delay.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #008000;\">METHOD 3) ASYNCHRONOUS WITH TIMEOUT<\/span><\/h3>\n<div class=\"ref-head\">3-async-timeout.js<\/div>\n<pre><code>\/\/ (A) ASYNCHRONOUS FUNCTION\r\nasync function demo () {\r\n  \/\/ (A1) DO SOMETHING\r\n  console.log(\"First\");\r\n \r\n  \/\/ (A2) WAIT 2 SECONDS\r\n  await new Promise(res =&gt; setTimeout(res, 2000));\r\n \r\n  \/\/ (A3) PROCEED\r\n  console.log(\"Second\");\r\n}\r\n \r\n\/\/ (B) GO!\r\ndemo();\r\n<\/code><\/pre>\n<p>Lastly, this should be pretty self-explanatory even if you have not touched on asynchronous functions &#8211; <code>await new Promise(res =&gt; setTimeout(res, 2000))<\/code> will wait for 2 seconds before proceeding.\u00a0I personally prefer this method, as it is non-blocking &#8211; <code>demo()<\/code> will &#8220;wait&#8221; in parallel while other scripts can continue to load and run.<\/p>\n<p>&nbsp;<\/p>\n<div id=\"ezoic-pub-ad-placeholder-106\"><\/div>\n<p>&nbsp;<\/p>\n<div id=\"sec-better\" class=\"sec-head\" style=\"background: #ffffe0;\">\n<h2 class=\"in-head-d\">A POSSIBLY BETTER WAY<\/h2>\n<p>If you are trying to &#8220;wait until something loads&#8221; or &#8220;pause until the process is complete&#8221; &#8211; Javascript is event-driven and here&#8217;s a better solution.<\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #008000;\">JAVASCRIPT EVENTS<\/span><\/h3>\n<div class=\"ref-head\">4-event.html<\/div>\n<pre><code>&lt;img src=\"demo.png\" id=\"demo\"&gt;\r\n&lt;script&gt;\r\n\/\/ (A) IMAGE LOADED\r\ndocument.getElementById(\"demo\").addEventListener(\"load\", () =&gt; {\r\n  console.log(\"Image loaded\");\r\n});\r\n \r\n\/\/ (B) PAGE READY\/LOADED\r\nwindow.addEventListener(\"DOMContentLoaded\", () =&gt; {\r\n  console.log(\"Page ready\");\r\n});\r\nwindow.addEventListener(\"load\", () =&gt; {\r\n  console.log(\"Page loaded\");\r\n});\r\n&lt;\/script&gt;<\/code><\/pre>\n<p>Yes, there&#8217;s no need to do all those &#8220;funky wait delays&#8221;. Javascript is event-driven, we only need to define &#8220;do X when Y is fully loaded&#8221;.<\/p>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #008000;\">CUSTOM EVENTS<\/span><\/h3>\n<div class=\"ref-head\">5-event.html<\/div>\n<pre><code>\/\/ (A) ASYNC FUNCTION TO DO SOMETHING\r\n\/\/ * DISPATCH \"FOO\" EVENT WHEN COMPLETE\r\nasync function demo () {\r\n  for (let i=0; i&lt;=1000; i++) {\r\n    if (i == 1000) { window.dispatchEvent(new Event(\"foo\")); }\r\n  }\r\n}\r\n \r\n\/\/ (B) LISTEN TO CUSTOM \"FOO\" EVENT\r\nwindow.addEventListener(\"foo\", () =&gt; {\r\n  console.log(\"Demo function has finished\");\r\n});\r\n \r\n\/\/ (C) GO!\r\ndemo();<\/code><\/pre>\n<p>Trying to wait until a function has finished? Dispatch your own custom event&#8230; Or just call another function when it ends.<\/p>\n<p>&nbsp;<\/p>\n<div id=\"ezoic-pub-ad-placeholder-107\"><\/div>\n<p>&nbsp;<\/p>\n<div id=\"sec-extra\" class=\"sec-head\" style=\"background: #f8d5ff;\">\n<h2 class=\"in-head-d\">EXTRAS<\/h2>\n<p>That&#8217;s all for this guide, and here is a small section on some extras and links that may be useful to you.<\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #008000;\">LINKS &amp; REFERENCES<\/span><\/h3>\n<ul>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Learn\/JavaScript\/Building_blocks\/Events\" target=\"_blank\" rel=\"noopener\">Introduction To Events<\/a> &#8211; MDN<\/li>\n<li><a href=\"https:\/\/www.sitepoint.com\/delay-sleep-pause-wait\/\" target=\"_blank\" rel=\"noopener noreferrer\">Delay, Sleep, Pause, &amp; Wait in JavaScript<\/a> &#8211; SitePoint<\/li>\n<li><a href=\"https:\/\/flaviocopes.com\/javascript-sleep\/\" target=\"_blank\" rel=\"noopener noreferrer\">How to make your JavaScript functions sleep<\/a> &#8211; Flavio Copes<\/li>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/async_function\" target=\"_blank\" rel=\"noopener noreferrer\">Async Function<\/a> &#8211; MDN<\/li>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Promise\" target=\"_blank\" rel=\"noopener noreferrer\">Promise<\/a> &#8211; MDN<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<div id=\"sec-end\" class=\"sec-head\" style=\"background: #f1f1f1;\">\n<h2 class=\"in-head-d\">THE END<\/h2>\n<p>Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!<\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Welcome to a quick tutorial on how to pause in Javascript. Bad news, there are no native implementations of pause in Javascript. But we can simulate pause, wait, sleep, or delay in Javascript via various means: Loop until a certain time has passed &#8211; var now = Date.now(), end = now + 1000; while (now [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":21728,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"default","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"default","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"set","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[15],"tags":[],"class_list":["post-5536","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-js"],"_links":{"self":[{"href":"https:\/\/code-boxx.com\/wp-json\/wp\/v2\/posts\/5536"}],"collection":[{"href":"https:\/\/code-boxx.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-boxx.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-boxx.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/code-boxx.com\/wp-json\/wp\/v2\/comments?post=5536"}],"version-history":[{"count":0,"href":"https:\/\/code-boxx.com\/wp-json\/wp\/v2\/posts\/5536\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-boxx.com\/wp-json\/wp\/v2\/media\/21728"}],"wp:attachment":[{"href":"https:\/\/code-boxx.com\/wp-json\/wp\/v2\/media?parent=5536"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-boxx.com\/wp-json\/wp\/v2\/categories?post=5536"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-boxx.com\/wp-json\/wp\/v2\/tags?post=5536"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}