JavaScript's async function has the capability to halt execution on its own accord

Presented here is a JavaScript async function designed to populate a sudoku board with numbers, essentially solving the puzzle. To enhance the user experience and showcase the recursion and backtracking algorithm in action, a sleeper function is utilized between each number insertion. However, an issue arises where the function abruptly stops after inserting the fifteenth number. What exactly could be causing this unexpected halt?

var finalInd;

function sleep() {
    console.log("happy")
    return new Promise(resolve => setTimeout(resolve, 100));
}


async function solve () {

    allowed = false;
    var empty = findEmptySpace();

    if(!empty) {
        return true;
    }

    for(let i=1; i<10; i++) {

        if(checkDuplicates(board, i, empty)) {

            board[empty[0]][empty[1]] = i;
            finalInd = (empty[0]*9) + empty[1];

            await sleep()
            funcId("board").children[finalInd].innerHTML = i;

            if(solve(board)) {
                return true;
            }
            
            board[empty[0]][empty[1]] = 0;
            
            funcId("board").children[finalInd].innerHTML = 0;
        }
    }

    funcId("board").children[0].innerHTML = board[0][0];
    return false;

}


function checkDuplicates (board, num, empty) {
    for(let i=0; i<9; i++) {
        if(board[empty[0]][i] == num && empty[1] != i) {
            return false;
        }
    }

    for(let i=0; i<9; i++) {
        if(board[i][empty[1]] == num && empty[0] != i) {
            return false;
        }
    }

    var x = Math.floor(empty[1]/3);
    var y = Math.floor(empty[0]/3);

    for(let i=(y*3); i<(y*3)+3; i++) {
        for(let j=(x*3); j<(x*3)+3; j++) {
            if(board[i][j] == num && i != empty[0] && j != empty[1]) {
                return false;
            }
        }
    }

    return true;

}


function findEmptySpace () {

    for(let i=0; i<9; i++) {
        for(let j=0; j<9; j++) {
            if(board[i][j] == 0) {
                return [i, j];
            }
        }
    }

}

https://i.sstatic.net/vfR5E.jpg

Answer №1

Perhaps you overlooked adding the await keyword before the recursive call to solve. This is essential to ensure that it returns a promise, as without it the function may terminate prematurely.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passing an ID via Link to retrieve data with getServerSideProps in Next.js

I have several alert components. From each of these components, I aim to pass the itm._id and receive it in [itm].jsx within the same folder. In [itm].jsx, I intend to utilize it in the getServerSideProps function for fetching data. Below is a snippet fro ...

Steps to automatically populate the dropdown upon page load

Hello, I have a question regarding setting a value to a dropdown list in JavaScript. Currently, I am trying to execute this function during the onload event of the body tag. However, I am facing issues with setting the value. Below is the code: function s ...

Access the extended controller and call the core controller function without directly interacting with the core controller

i have a core controller that contains an array called vm.validationTypes with only 2 objects. I need to add 3 or 4 more objects to this array. to achieve this, i created another controller by extending the core controller: // CustomValidation angular.m ...

What is the best way to extract menu and submenu information from an array?

I'm in the process of building a webpage with the help of smart admin and I'm facing an issue with displaying left menu data properly. The data is being retrieved from an array and I need to arrange the menus and submenus based on the parent ID o ...

Django: The Art of Rejuvenating Pages

Consider the following code snippet which updates the timestamp of a database model whenever it is accessed: def update_timestamp(request): entry = Entry.objects.filter(user=request.user) entry.update(timestamp=timezone.now()) return HttpRespo ...

Angular.js is experiencing difficulties when using the input value attribute in conjunction with ng-model

I've been hard at work on an app that allows users to edit items, with those changes updating in a database. To prevent empty form submissions, I automatically fill the input fields with the current item's information. form.form-update(method="p ...

What is the best way to implement data validation for various input fields using JavaScript with a single function?

Users can input 5 numbers into a form, each with the same ID but a different name. I want to validate each input and change the background color based on the number entered - red for 0-5, green for 6-10. I wrote code to change the color for one input box, ...

Effortlessly refresh a data object in Vue.js without relying on a function

I need assistance with the following: <Checkbox label="View" :initialState="data.something" @updateStatus="updateCheckbox" > </Checkbox> The variable data.something is a b ...

The POST request made using Postman shows an empty Node.js/Express req.body

Here is the current code snippet I am working with: var express = require('express'); var router = express.Router(); var db = require('../helpers/db'); var data = { "1": 127, "2": 236, "3": 348 } router.get('/', ...

Is there a way to update a div element with an image without having to refresh

Currently working on a project for my studies where I am reading the x and y coordinates from a touch pad and drawing it in real time using PHP. I have created a draw page that takes these coordinates and displays them on an image, which is then shown on ...

Can you tell me the specific parameter used in the beforeSend function in jQuery?

I have been examining some instances of the beforeSend callback function. Sometimes, these examples include an input parameter: beforeSend:function(req) or beforeSend:function(xhr). I assume that this parameter represents the XMLHTTPRequest of the jquery ...

Utilizing ES6 array methods to convert multidimensional arrays into chart-ready data

Seeking help with converting an array to a specific data format for chart display. The chrart.js library requires data in the following format: dataset = [ { label: 'one', data: []}, {label: 'two', data: []} ]; I ...

Every time a button is clicked on the interface, a new element or button will appear. This functionality is made possible through

Currently diving into a new React.js project as a beginner. I have a little challenge in the code snippet below - looking to add a button that displays "Hello World" every time it's clicked using setState. Can anyone guide me on enhancing the DisplayM ...

What is the best approach for submitting a form with data through a POST request in an Ionic application?

I am facing an issue while trying to make a POST request in Ionic for submitting a form with an array of data. Surprisingly, it works perfectly fine when I test it on POSTMAN. Although I attempted to use this form, it did not yield the desired results: ...

Is there a way to hide the <v-otp-input> field in a Vue.js application?

For more information, please visit https://www.npmjs.com/package/@bachdgvn/vue-otp-input <script> export default { name: 'App', methods: { handleOnComplete(value) { console.log('OTP completed: ', value); } ...

Unable to locate module in node_modules directory when attempting to import an image into TS

In my .tsx file, I am encountering an issue with the following code snippet: import L from 'leaflet'; import icon from 'leaflet/dist/images/marker-icon.png'; import iconShadow from 'leaflet/dist/images/marker-shadow.png'; The ...

Unable to locate a type definition file for module 'vue-xxx'

I keep encountering an error whenever I attempt to add a 3rd party Vue.js library to my project: Could not find a declaration file for module 'vue-xxx' Libraries like 'vue-treeselect', 'vue-select', and 'vue-multiselect ...

Creating a dedicated class or module specifically designed for handling import and export tasks is a highly efficient approach towards stream

Exploring different ways to import multiple classes into a single class file: import myClass1 'pathto1'; import myClass2 'pathto2'; import myClassn 'pathton'; Seeking a simpler method using one file (class export) with al ...

Blunder! Error code EINVALIDTAGNAME encountered while trying to install a package

I'm encountering an issue while trying to add a new package to my React application. The error I'm receiving is: $ npm install xlsx npm ERR! code EINVALIDTAGNAME npm ERR! Invalid tag name "react-scripts start": Tags may not have any characters th ...

Could we confirm if this straightforward string is considered valid JSON data?

There are numerous intricate questions on Stack Overflow about whether a complex structure is considered valid JSON. However, what about something much simpler? "12345" Would the provided code snippet be considered valid JSON? ...